﻿using Dapper;
using Estsh.Core.Base;
using Estsh.Core.Dapper;
using Estsh.Core.Wms.IRepositories;
using Estsh.Core.Model.Result;
using Estsh.Core.Repositories;
using System.Collections;
using System.Data;
using System.Text;
using System.Security.Cryptography;
using System.Text.Json;
using Estsh.Core.Models;
using Newtonsoft.Json.Linq;
using Estsh.Core.Model.EnumUtil;
using Estsh.Core.Model.Extend;
using Estsh.Core.Model.Extend.Models;
using Estsh.Core.Model.Extend.IFModels;

namespace Estsh.Core.Wms.Repositories
{
    public class InterfaceMasterRepository : BaseRepository<SapPt>, IInterfaceMasterRepository
    {
        public InterfaceMasterRepository(DapperDbContext _dapperDbContext) : base(_dapperDbContext)
        {

        }
        #region 物料
        /// <summary>
        /// 获取物料主数据的数据
        /// </summary>
        /// <returns></returns>
        public List<SapPt_Extend> GetMaterialMasterInfo()
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                StringBuilder sql = new StringBuilder(1024);
                sql.Append("SELECT top 50000 * FROM sap_pt (nolock) ");
                sql.Append("WHERE  SYNFLG = 'N' ");
                sql.Append("ORDER BY RECTIM  ");

                return dbConn.Query<SapPt_Extend>(sql.ToString()).ToList();
            }
        }
        //添加物料接口表到物料表
        public bool InsertMaterialMasterInfo(List<SapPt_Extend> sapPts)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                List<string> sqlList;
                List<DynamicParameters> parametersList;
                StringBuilder SqlStringBuilder;
                DynamicParameters parameters;
                SapPt_Extend sapPt = new SapPt_Extend();
                try
                {
                    for (int i = 0; i < sapPts.Count; i++)
                    {
                        sqlList = new List<string>();
                        parametersList = new List<DynamicParameters>();
                        sapPt = sapPts[i];

                        SqlStringBuilder = new StringBuilder(1024);
                        parameters = new DynamicParameters();

                        StringBuilder stringBuilder = new StringBuilder();
                        stringBuilder.Append(" SELECT * from sys_part (nolock) WHERE part_no='" + sapPt.Matnr + "'");
                        List<SysPart> sysParts = dbConn.Query<SysPart>(stringBuilder.ToString()).ToList();

                        if (sysParts.Count > 0)
                        {
                            StringBuilder factoryStringBuilder = new StringBuilder(1024);
                            factoryStringBuilder.Append("select * from sys_factory (nolock) where factory_code='" + sapPt.Werks + "'");//工厂代码获取工厂ID
                            SysFactory sysFactory = dbConn.Query<SysFactory>(factoryStringBuilder.ToString()).FirstOrDefault();

                            SqlStringBuilder = new StringBuilder(1024);
                            SqlStringBuilder.Append("UPDATE dbo.sys_part ");
                            SqlStringBuilder.Append("   SET part_no = @partNo ,part_spec = @partSpec,part_spec2=@partSpec2,part_type=@partType ");
                            SqlStringBuilder.Append("	  ,unit=@unit ,default_box_qty = @defaultBoxQty ");
                            SqlStringBuilder.Append("      ,part_abc = @partAbc ,part_group = @partGroup,option1=@option1 ");
                            SqlStringBuilder.Append("      ,factory_id = @factoryId ,factory_code = @factoryCode ");
                            SqlStringBuilder.Append("      ,enabled = @enabled ,update_userid = @updateUserid ");
                            SqlStringBuilder.Append("      ,update_time = @updateTime ,isbatch=@isbatch");
                            SqlStringBuilder.Append("      ,cgtqq=@cgtqq ,cgpc=@cgpc ,wldj=@wldj");
                            SqlStringBuilder.Append("      ,revupper=@revupper ,revdowmper=@revdowmper");
                            SqlStringBuilder.Append("      ,cfupper=@cfupper ,cfdowmper=@cfdowmper");
                            SqlStringBuilder.Append("      ,instockupper=@instockupper,instockdowmper=@instockdowmper");
                            SqlStringBuilder.Append("      ,zrstock=@zrstock,dock=@dock,netweight=@netweight");
                            SqlStringBuilder.Append("      ,pricemethod=@pricemethod,minpurchase=@minpurchase");
                            SqlStringBuilder.Append("      ,safetystock=@safetystock,exemption=@exemption");
                            SqlStringBuilder.Append(" WHERE part_no = @partNo AND factory_code = @factoryCode ");
                            sqlList.Add(SqlStringBuilder.ToString());
                            parameters.Add("@partNo", sapPt.Matnr);//物料编码
                            parameters.Add("@partSpec", sapPt.Zzppmatnr);//物料简码
                            parameters.Add("@partSpec2", sapPt.Maktx);//物料描述

                            if (sapPt.Mtart == "Z010")
                            {
                                parameters.Add("@partType", "1");//成品
                            }
                            else if (sapPt.Mtart == "Z020")
                            {
                                parameters.Add("@partType", "1");//半成品
                            }
                            else if (sapPt.Mtart == "Z030")
                            {
                                parameters.Add("@partType", "0");//原材料
                            }
                            else if (sapPt.Mtart == "Z040")
                            {
                                parameters.Add("@partType", "2");//转手件
                            }
                            else if (sapPt.Mtart == "Z050")
                            {
                                parameters.Add("@partType", "3");//售后服务件
                            }
                            else if (sapPt.Mtart == "Z060")
                            {
                                parameters.Add("@partType", "4");//支给件
                            }
                            else if (sapPt.Mtart == "Z090")
                            {
                                parameters.Add("@partType", "5");//间接物料
                            }
                            else
                            {
                                parameters.Add("@partType", "0");//其他
                            }

                            parameters.Add("@unit", sapPt.Meins);//基本单位
                            parameters.Add("@defaultBoxQty", sapPt.Bstrf);//最小包装数量
                            parameters.Add("@partAbc", sapPt.Maabc);//分类（ABCDE）
                            parameters.Add("@partGroup", sapPt.Wgbez);//物料组描述
                            parameters.Add("@option1", sapPt.Spart);//产品组
                            parameters.Add("@factoryId", sysFactory == null ? 0 : sysFactory.FactoryId);//工厂ID
                            parameters.Add("@factoryCode", sapPt.Werks);//工厂代码
                            parameters.Add("@enabled", 'Y');//启用
                            parameters.Add("@updateUserid", 0);//更新人
                            parameters.Add("@updateTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));//更新日期
                            parameters.Add("@isbatch", sapPt.IsBatch);
                            parameters.Add("@cgtqq", sapPt.Cgtqq);
                            parameters.Add("@cgpc", sapPt.Cgpc);
                            parameters.Add("@wldj", sapPt.Wldj);
                            parameters.Add("@revupper", sapPt.RevUpper);
                            parameters.Add("@revdowmper", sapPt.RevDowmper);
                            parameters.Add("@cfupper", sapPt.CfUpper);
                            parameters.Add("@cfdowmper", sapPt.CfDowmper);
                            parameters.Add("@instockupper", sapPt.InStockUpper);
                            parameters.Add("@instockdowmper", sapPt.InStockDowmper);
                            parameters.Add("@zrstock", sapPt.Zrstock);
                            parameters.Add("@dock", sapPt.Dock);
                            parameters.Add("@netweight", sapPt.Netweight);
                            parameters.Add("@pricemethod", sapPt.PriceMethod);
                            parameters.Add("@minpurchase", sapPt.MinPurchase);
                            parameters.Add("@safetystock", sapPt.SafetyStock);
                            parameters.Add("@exemption", sapPt.Exemption);

                            parametersList.Add(parameters);

                        }
                        else
                        {
                            StringBuilder factoryStringBuilder = new StringBuilder(1024);
                            factoryStringBuilder.Append("select * from sys_factory (nolock) where factory_code='" + sapPt.Werks + "'");//工厂代码获取工厂ID
                            SysFactory sysFactory = dbConn.Query<SysFactory>(factoryStringBuilder.ToString()).FirstOrDefault();

                            SqlStringBuilder.Append("INSERT INTO dbo.sys_part(part_no,part_spec,part_spec2,part_type,unit,default_box_qty,part_abc ");
                            SqlStringBuilder.Append("		   ,part_group,option1,factory_id,factory_code,enabled,create_userid,create_time ");
                            SqlStringBuilder.Append(" ,isbatch,cgtqq,cgpc,wldj,cfupper,cfdowmper,instockupper,instockdowmper,zrstock,dock");
                            SqlStringBuilder.Append(" ,netweight,pricemethod,minpurchase,safetystock,exemption)");
                            SqlStringBuilder.Append("     VALUES(@partNo,@partSpec,@partSpec2,@partType,@unit,@defaultBoxQty,@partAbc,@partGroup,@option1,@factoryId ");
                            SqlStringBuilder.Append("           ,@factoryCode,@enabled,@createUserid,@createTime ");
                            SqlStringBuilder.Append(" ,@isbatch,@cgtqq,@cgpc,@wldj,@cfupper,@cfdowmper,@instockupper,@instockdowmper,@zrstock,@dock");
                            SqlStringBuilder.Append(" ,@netweight,@pricemethod,@minpurchase,@safetystock,@exemption)");
                            sqlList.Add(SqlStringBuilder.ToString());
                            parameters.Add("@partNo", sapPt.Matnr);//物料编码
                            parameters.Add("@partSpec", sapPt.Zzppmatnr);//物料简码
                            parameters.Add("@partSpec2", sapPt.Maktx);//物料描述

                            if (sapPt.Mtart == "Z010")
                            {
                                parameters.Add("@partType", "1");//成品
                            }
                            else if (sapPt.Mtart == "Z020")
                            {
                                parameters.Add("@partType", "1");//半成品
                            }
                            else if (sapPt.Mtart == "Z030")
                            {
                                parameters.Add("@partType", "0");//原材料
                            }
                            else if (sapPt.Mtart == "Z040")
                            {
                                parameters.Add("@partType", "2");//转手件
                            }
                            else if (sapPt.Mtart == "Z050")
                            {
                                parameters.Add("@partType", "3");//售后服务件
                            }
                            else if (sapPt.Mtart == "Z060")
                            {
                                parameters.Add("@partType", "4");//支给件
                            }
                            else if (sapPt.Mtart == "Z090")
                            {
                                parameters.Add("@partType", "5");//间接物料
                            }
                            else
                            {
                                parameters.Add("@partType", "0");//其他
                            }

                            parameters.Add("@partSpec2", sapPt.Maktx);//物料描述

                            parameters.Add("@unit", sapPt.Meins);//基本单位
                            parameters.Add("@defaultBoxQty", sapPt.Bstrf);//最小包装数量
                            parameters.Add("@partAbc", sapPt.Maabc);//分类（ABCDE）
                            parameters.Add("@partGroup", sapPt.Wgbez);//物料组描述
                            parameters.Add("@option1", sapPt.Spart);//产品组
                            parameters.Add("@factoryId", sysFactory == null ? 0 : sysFactory.FactoryId);//工厂ID
                            parameters.Add("@factoryCode", sapPt.Werks);//工厂代码
                            parameters.Add("@enabled", 'Y');//启用
                            parameters.Add("@createUserid", 0);//创建人
                            parameters.Add("@createTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));//创建日期
                            parameters.Add("@isbatch", sapPt.IsBatch);
                            parameters.Add("@cgtqq", sapPt.Cgtqq);
                            parameters.Add("@cgpc", sapPt.Cgpc);
                            parameters.Add("@wldj", sapPt.Wldj);
                            parameters.Add("@revupper", sapPt.RevUpper);
                            parameters.Add("@revdowmper", sapPt.RevDowmper);
                            parameters.Add("@cfupper", sapPt.CfUpper);
                            parameters.Add("@cfdowmper", sapPt.CfDowmper);
                            parameters.Add("@instockupper", sapPt.InStockUpper);
                            parameters.Add("@instockdowmper", sapPt.InStockDowmper);
                            parameters.Add("@zrstock", sapPt.Zrstock);
                            parameters.Add("@dock", sapPt.Dock);
                            parameters.Add("@netweight", sapPt.Netweight);
                            parameters.Add("@pricemethod", sapPt.PriceMethod);
                            parameters.Add("@minpurchase", sapPt.MinPurchase);
                            parameters.Add("@safetystock", sapPt.SafetyStock);
                            parameters.Add("@exemption", sapPt.Exemption);
                            parametersList.Add(parameters);
                        }

                        SqlStringBuilder = new StringBuilder(1024);
                        SqlStringBuilder.Append("update SAP_PT set SYNFLG='Y',SYNTIM=@SYNTIM,ERRMSG=''  where GUID=@GUID ");//更新同步状态
                        sqlList.Add(SqlStringBuilder.ToString());

                        parameters = new DynamicParameters();
                        parameters.Add("@GUID", sapPt.Guid);//ID
                        parameters.Add("@SYNTIM", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));//同步时间
                        parametersList.Add(parameters);

                        bool staResult = ExecuteTransaction(sqlList, parametersList);
                        if (staResult == false)
                        {
                            sqlList = new List<string>();
                            parametersList = new List<DynamicParameters>();
                            SqlStringBuilder = new StringBuilder(1024);
                            SqlStringBuilder.Append("update SAP_PT set SYNFLG='E',ERRMSG=@ERRMSG,SYNTIM=@SYNTIM  where GUID=@GUID ");//更新同步状态
                            sqlList.Add(SqlStringBuilder.ToString());

                            parameters = new DynamicParameters();
                            parameters.Add("@GUID", sapPt.Guid);//ID
                            parameters.Add("@ERRMSG", "同步错误，请检查接口数据！");//错误
                            parameters.Add("@SYNTIM", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));//同步时间
                            parametersList.Add(parameters);
                            ExecuteTransaction(sqlList, parametersList);
                            return false;
                        }
                    }
                    return true;
                }
                catch (Exception ex)
                {
                    sqlList = new List<string>();
                    parametersList = new List<DynamicParameters>();
                    SqlStringBuilder = new StringBuilder(1024);
                    SqlStringBuilder.Append("update SAP_PT set SYNFLG='E',ERRMSG=@ERRMSG,SYNTIM=@SYNTIM  where GUID=@GUID ");//更新同步状态
                    sqlList.Add(SqlStringBuilder.ToString());

                    parameters = new DynamicParameters();
                    parameters.Add("@GUID", sapPt.Guid);//ID
                    parameters.Add("@ERRMSG", ex.Message);//错误
                    parameters.Add("@SYNTIM", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));//同步时间
                    parametersList.Add(parameters);
                    ExecuteTransaction(sqlList, parametersList);
                    return false;
                }
            }
        }

        /// <summary>
        /// 获取供应商基本信息
        /// </summary>
        /// <returns></returns>
        public List<SapSu> GetSupplierMasterInfo()
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                StringBuilder sql = new StringBuilder(1024);
                sql.Append("SELECT top 5000 * FROM sap_su (nolock) ");
                sql.Append("WHERE  SYNFLG = 'N' ");
                sql.Append("ORDER BY RECTIM  ");

                return dbConn.Query<SapSu>(sql.ToString()).ToList();
            }
        }

        /// <summary>
        /// 添加供应商接口表到供应商表
        /// </summary>
        /// <param name="sapSu"></param>
        /// <returns></returns>
        public bool InsertSupplierMasterInfo(List<SapSu> sapSus)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                SapSu sapSu = new SapSu();
                StringBuilder factoryStringBuilder = new StringBuilder(1024);
                factoryStringBuilder.Append("select * from sys_factory (nolock) where enabled='Y'");//工厂代码获取工厂ID
                List<SysFactory> sysFactory = dbConn.Query<SysFactory>(factoryStringBuilder.ToString()).ToList();
                for (int k = 0; k < sysFactory.Count; k++)
                {
                    StringBuilder SqlStringBuilder = new StringBuilder(1024);
                    DynamicParameters parameters = new DynamicParameters();

                    for (int i = 0; i < sapSus.Count; i++)
                    {
                        List<string> sqlList = new List<string>();
                        List<DynamicParameters> parametersList = new List<DynamicParameters>();
                        sapSu = sapSus[i];
                        StringBuilder stringBuilder = new StringBuilder();
                        stringBuilder.Append(" SELECT * from sys_vendor (nolock) WHERE vendor_code='" + sapSu.Lifnr + "' AND factory_code = '" + sysFactory[k].FactoryCode + "' ");
                        List<SysVendor> sysVendors = dbConn.Query<SysVendor>(stringBuilder.ToString()).ToList();
                        if (sysVendors.Count > 0)
                        {
                            SqlStringBuilder = new StringBuilder(1024);
                            SqlStringBuilder.Append(" UPDATE dbo.sys_vendor ");
                            SqlStringBuilder.Append("   SET vendor_code = @vendorCode ,vendor_name = @vendorName ,vendor_tel = @vendorTel ");
                            SqlStringBuilder.Append("      ,vendor_addr = @vendorAddr ,vendor_mail = @vendorMail ,factory_id = @factoryId ");
                            SqlStringBuilder.Append("      ,factory_code = @factoryCode ,enabled = @enabled ,update_userid = @updateUserid ");
                            SqlStringBuilder.Append("      ,update_time = @updateTime ");
                            SqlStringBuilder.Append(" WHERE vendor_code = @vendorCode AND factory_code = @factoryCode ");

                            sqlList.Add(SqlStringBuilder.ToString());

                            parameters = new DynamicParameters();
                            parameters.Add("@vendorCode", sapSu.Lifnr);//物料编码
                            parameters.Add("@vendorName", sapSu.Name1);//物料描述
                            parameters.Add("@vendorAddr", sapSu.Stras);//供应商地址
                            parameters.Add("@vendorTel", sapSu.Telf1);//联系电话
                            parameters.Add("@vendorMail", sapSu.Pstl2);//邮箱

                            parameters.Add("@factoryId", sysFactory[k].FactoryId);//工厂ID
                            parameters.Add("@factoryCode", sysFactory[k].FactoryCode);//工厂代码

                            parameters.Add("@enabled", 'Y');//启用
                            parameters.Add("@updateUserid", 0);//更新人
                            parameters.Add("@updateTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));//更新日期

                            parametersList.Add(parameters);
                        }
                        else
                        {
                            SqlStringBuilder = new StringBuilder(1024);
                            SqlStringBuilder.Append("INSERT INTO dbo.sys_vendor(vendor_code,vendor_name,vendor_tel,vendor_addr ");
                            SqlStringBuilder.Append("           ,vendor_mail,factory_id,factory_code,enabled,create_userid,create_time) ");
                            SqlStringBuilder.Append("     VALUES(@vendorCode,@vendorName,@vendorTel,@vendorAddr ");
                            SqlStringBuilder.Append("           ,@vendorMail,@factoryId,@factoryCode,@enabled,@createUserid,@createTime) ");

                            sqlList.Add(SqlStringBuilder.ToString());

                            parameters = new DynamicParameters();
                            parameters.Add("@vendorCode", sapSu.Lifnr);//物料编码
                            parameters.Add("@vendorName", sapSu.Name1);//物料描述
                            parameters.Add("@vendorAddr", sapSu.Stras);//供应商地址
                            parameters.Add("@vendorTel", sapSu.Telf1);//联系电话
                            parameters.Add("@vendorMail", sapSu.Pstl2);//邮箱

                            parameters.Add("@factoryId", sysFactory[k].FactoryId);//工厂ID
                            parameters.Add("@factoryCode", sysFactory[k].FactoryCode);//工厂代码

                            parameters.Add("@enabled", 'Y');//启用
                            parameters.Add("@createUserid", 0);//创建人
                            parameters.Add("@createTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));//创建日期

                            parametersList.Add(parameters);

                        }

                        SqlStringBuilder = new StringBuilder(1024);
                        SqlStringBuilder.Append("update SAP_SU set SYNFLG='Y',SYNTIM=@SYNTIM where GUID=@GUID ");//更新同步状态
                        sqlList.Add(SqlStringBuilder.ToString());

                        parameters = new DynamicParameters();
                        parameters.Add("@GUID", sapSu.Guid);//ID
                        parameters.Add("@SYNTIM", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));//同步时间
                        parametersList.Add(parameters);

                        bool staResult = ExecuteTransaction(sqlList, parametersList);
                        if (staResult == false)
                        {
                            sqlList = new List<string>();
                            parametersList = new List<DynamicParameters>();
                            SqlStringBuilder = new StringBuilder(1024);
                            SqlStringBuilder.Append("update SAP_SU set SYNFLG='E',ERRMSG=@ERRMSG,SYNTIM=@SYNTIM  where GUID=@GUID ");//更新同步状态
                            sqlList.Add(SqlStringBuilder.ToString());

                            parameters = new DynamicParameters();
                            parameters.Add("@GUID", sapSu.Guid);//ID
                            parameters.Add("@ERRMSG", "同步错误，请检查接口数据！");//错误
                            parameters.Add("@SYNTIM", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));//同步时间
                            parametersList.Add(parameters);
                            ExecuteTransaction(sqlList, parametersList);
                            return false;
                        }
                    }
                }
                return true;
            }
        }

        /// <summary>
        /// 获取客户基本信息
        /// </summary>
        /// <returns></returns>
        public List<SapCu> GetCustomerMasterInfo()
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                StringBuilder sql = new StringBuilder(1024);
                sql.Append("SELECT top 5000 * FROM sap_cu (nolock) ");
                sql.Append("WHERE  SYNFLG = 'N' ");
                sql.Append("ORDER BY RECTIM  ");

                return dbConn.Query<SapCu>(sql.ToString()).ToList();
            }
        }

        /// <summary>
        /// 添加客户接口表到供应商表
        /// </summary>
        /// <param name="sapCu"></param>
        /// <returns></returns>
        public bool InsertCustomerMasterInfo(List<SapCu> sapCus)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {

                SapCu sapCu = new SapCu();
                StringBuilder factoryStringBuilder = new StringBuilder(1024);
                factoryStringBuilder.Append("select * from sys_factory (nolock) where enabled='Y'");//工厂代码获取工厂ID
                List<SysFactory> sysFactory = dbConn.Query<SysFactory>(factoryStringBuilder.ToString()).ToList();
                for (int k = 0; k < sysFactory.Count; k++)
                {
                    StringBuilder SqlStringBuilder = new StringBuilder(1024);
                    DynamicParameters parameters = new DynamicParameters();

                    for (int i = 0; i < sapCus.Count; i++)
                    {
                        List<string> sqlList = new List<string>();
                        List<DynamicParameters> parametersList = new List<DynamicParameters>();
                        sapCu = sapCus[i];
                        StringBuilder stringBuilder = new StringBuilder();
                        stringBuilder.Append(" SELECT * from sys_customer (nolock) WHERE customer_code='" + sapCu.Kunnr + "' AND factory_code = '" + sysFactory[k].FactoryCode + "' ");
                        List<SysCustomer> sysCustomers = dbConn.Query<SysCustomer>(stringBuilder.ToString()).ToList();
                        if (sysCustomers.Count > 0)
                        {
                            SqlStringBuilder = new StringBuilder(1024);
                            SqlStringBuilder.Append("UPDATE dbo.sys_customer ");
                            SqlStringBuilder.Append("   SET customer_code = @customerCode ,customer_name = @customerName ");
                            SqlStringBuilder.Append("      ,customer_tel = @customerTel ,customer_addr = @customerAddr ");
                            SqlStringBuilder.Append("      ,factory_id = @factoryId ,factory_code = @factoryCode ");
                            SqlStringBuilder.Append("      ,enabled = @enabled ,update_userid = @updateUserid ");
                            SqlStringBuilder.Append("      ,update_time = @updateTime ");
                            SqlStringBuilder.Append(" WHERE customer_code = @customerCode AND factory_code = @factoryCode ");

                            sqlList.Add(SqlStringBuilder.ToString());

                            parameters = new DynamicParameters();
                            parameters.Add("@customerCode", sapCu.Kunnr);//客户编号
                            parameters.Add("@customerName", sapCu.Name1);//客户名称
                            parameters.Add("@customerAddr", sapCu.Stras);//客户地址
                            parameters.Add("@customerTel", sapCu.Telf1);//联系电话

                            parameters.Add("@factoryId", sysFactory[k].FactoryId);//工厂ID
                            parameters.Add("@factoryCode", sysFactory[k].FactoryCode);//工厂代码

                            parameters.Add("@enabled", 'Y');//启用
                            parameters.Add("@updateUserid", 0);//更新人
                            parameters.Add("@updateTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));//更新日期

                            parametersList.Add(parameters);
                        }
                        else
                        {
                            SqlStringBuilder = new StringBuilder(1024);
                            SqlStringBuilder.Append("INSERT INTO dbo.sys_customer(customer_code,customer_name,customer_tel,customer_addr ");
                            SqlStringBuilder.Append("           ,factory_id,factory_code,enabled,create_userid,create_time) ");
                            SqlStringBuilder.Append("     VALUES(@customerCode,@customerName,@customerTel,@customerAddr ");
                            SqlStringBuilder.Append("           ,@factoryId,@factoryCode,@enabled,@createUserid,@createTime) ");

                            sqlList.Add(SqlStringBuilder.ToString());

                            parameters = new DynamicParameters();
                            parameters.Add("@customerCode", sapCu.Kunnr);//客户编号
                            parameters.Add("@customerName", sapCu.Name1);//客户名称
                            parameters.Add("@customerAddr", sapCu.Stras);//客户地址
                            parameters.Add("@customerTel", sapCu.Telf1);//联系电话

                            parameters.Add("@factoryId", sysFactory[k].FactoryId);//工厂ID
                            parameters.Add("@factoryCode", sysFactory[k].FactoryCode);//工厂代码

                            parameters.Add("@enabled", 'Y');//启用
                            parameters.Add("@createUserid", 0);//创建人
                            parameters.Add("@createTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));//创建日期

                            parametersList.Add(parameters);
                        }

                        SqlStringBuilder = new StringBuilder(1024);
                        SqlStringBuilder.Append("update SAP_CU set SYNFLG='Y',SYNTIM=@SYNTIM  where GUID=@GUID ");//更新同步状态
                        sqlList.Add(SqlStringBuilder.ToString());

                        parameters = new DynamicParameters();
                        parameters.Add("@GUID", sapCu.Guid);//ID
                        parameters.Add("@SYNTIM", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));//同步时间
                        parametersList.Add(parameters);

                        bool staResult = ExecuteTransaction(sqlList, parametersList);
                        if (staResult == false)
                        {
                            sqlList = new List<string>();
                            parametersList = new List<DynamicParameters>();
                            SqlStringBuilder = new StringBuilder(1024);
                            SqlStringBuilder.Append("update SAP_CU set SYNFLG='E',ERRMSG=@ERRMSG,SYNTIM=@SYNTIM  where GUID=@GUID ");//更新同步状态
                            sqlList.Add(SqlStringBuilder.ToString());

                            parameters = new DynamicParameters();
                            parameters.Add("@GUID", sapCu.Guid);//ID
                            parameters.Add("@ERRMSG", "同步错误，请检查接口数据！");//错误
                            parameters.Add("@SYNTIM", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));//同步时间
                            parametersList.Add(parameters);
                            ExecuteTransaction(sqlList, parametersList);
                            return false;
                        }
                    }
                }
                return true;
            }
        }

        /// <summary>
        /// 获取物料号与客户物料号对照信息
        /// </summary>
        /// <returns></returns>
        public List<SapPtcpt> GetCustomerItemMasterInfo()
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                StringBuilder sql = new StringBuilder(1024);
                sql.Append("SELECT top 5000 * FROM sap_ptcpt (nolock) ");
                sql.Append("WHERE  SYNFLG = 'N' ");
                sql.Append("ORDER BY RECTIM  ");

                return dbConn.Query<SapPtcpt>(sql.ToString()).ToList();
            }
        }

        /// <summary>
        /// 添加物料号与客户物料号对照信息
        /// </summary>
        /// <param name="sapPtcpt"></param>
        /// <returns></returns>
        public bool InsertCustomerItemMasterInfo(List<SapPtcpt> sapPtcpts)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                SapPtcpt sapPtcpt = new SapPtcpt();
                StringBuilder factoryStringBuilder = new StringBuilder(1024);
                factoryStringBuilder.Append("select * from sys_factory (nolock) where enabled='Y'");//工厂代码获取工厂ID
                List<SysFactory> sysFactory = dbConn.Query<SysFactory>(factoryStringBuilder.ToString()).ToList();
                for (int k = 0; k < sysFactory.Count; k++)
                {
                    StringBuilder SqlStringBuilder = new StringBuilder(1024);
                    DynamicParameters parameters = new DynamicParameters();
                    for (int i = 0; i < sapPtcpts.Count; i++)
                    {
                        List<string> sqlList = new List<string>();
                        List<DynamicParameters> parametersList = new List<DynamicParameters>();
                        sapPtcpt = sapPtcpts[i];
                        StringBuilder partNoStringBuilder = new StringBuilder(1024);
                        partNoStringBuilder.Append("select * from sys_part (nolock) where part_no='" + sapPtcpt.Matnr + "' AND factory_code = '" + sysFactory[k].FactoryCode + "' ");//零件号ID
                        List<SysPart> sysPart = dbConn.Query<SysPart>(partNoStringBuilder.ToString()).ToList();

                        SqlStringBuilder = new StringBuilder(1024);
                        SqlStringBuilder.Append("select * from sys_customer_part (nolock) where customer_code='" + sapPtcpt.Kunnr + "' AND part_no='" + sapPtcpt.Matnr + "'");
                        List<SysCustomerPart> customerParts = dbConn.Query<SysCustomerPart>(SqlStringBuilder.ToString()).ToList();

                        if (customerParts.Count > 0)
                        {
                            SqlStringBuilder = new StringBuilder(1024);
                            SqlStringBuilder.Append("UPDATE dbo.sys_customer_part ");
                            SqlStringBuilder.Append("   SET customer_id = @customerId,customer_code = @customerCode ");
                            SqlStringBuilder.Append("      ,part_id = @partId,part_no = @partNo ");
                            SqlStringBuilder.Append("      ,cust_part_no = @custPartNo,enabled = @enabled ");
                            SqlStringBuilder.Append("      ,factory_id = @factoryId,factory_code = @factoryCode ");
                            SqlStringBuilder.Append("      ,update_userid = @updateUserid,update_time = @updateTime ");
                            SqlStringBuilder.Append(" WHERE  customer_code=@customerCode AND part_no=@partNo AND factory_code = @factoryCode ");

                            sqlList.Add(SqlStringBuilder.ToString());

                            StringBuilder customerStringBuilder = new StringBuilder(1024);
                            customerStringBuilder.Append("select * from sys_customer (nolock) where customer_code='" + sapPtcpt.Kunnr + "'");//客户信息
                            List<SysCustomer> sysCustomers = dbConn.Query<SysCustomer>(customerStringBuilder.ToString()).ToList();

                            parameters = new DynamicParameters();
                            if (sysCustomers.Count == 0)
                            {
                                parameters.Add("@customerId", 0);//客户id
                            }
                            else
                            {
                                parameters.Add("@customerId", sysCustomers[0].CustomerId);//客户id
                            }
                            parameters.Add("@customerCode", sapPtcpt.Kunnr);//客户编码
                            if (sysPart.Count == 0)
                            {
                                parameters.Add("@partId", 0);//物料ID
                            }
                            else
                            {
                                parameters.Add("@partId", sysPart[0].PartId);//物料ID
                            }
                            parameters.Add("@partNo", sapPtcpt.Matnr);//物料代码
                            parameters.Add("@custPartNo", sapPtcpt.Kdmat);//客户零件号

                            parameters.Add("@factoryId", sysFactory[k].FactoryId);//工厂ID
                            parameters.Add("@factoryCode", sysFactory[k].FactoryCode);//工厂代码

                            parameters.Add("@enabled", 'Y');//启用
                            parameters.Add("@updateUserid", 0);//修改人
                            parameters.Add("@updateTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));//修改日期
                            parametersList.Add(parameters);


                            SqlStringBuilder = new StringBuilder(1024);
                            SqlStringBuilder.Append("update SAP_PTCPT set SYNFLG='Y',SYNTIM=@SYNTIM  where GUID=@GUID ");//更新同步状态
                            sqlList.Add(SqlStringBuilder.ToString());

                            parameters = new DynamicParameters();
                            parameters.Add("@GUID", sapPtcpt.Guid);//ID
                            parameters.Add("@SYNTIM", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));//同步时间
                            parametersList.Add(parameters);
                        }
                        else
                        {
                            SqlStringBuilder = new StringBuilder(1024);
                            SqlStringBuilder.Append("INSERT INTO dbo.sys_customer_part(customer_id,customer_code,part_id,part_no ");
                            SqlStringBuilder.Append("           ,cust_part_no,factory_id,factory_code,enabled,create_userid,create_time) ");
                            SqlStringBuilder.Append("     VALUES(@customerId,@customerCode,@partId,@partNo,@custPartNo,@factoryId,@factoryCode,@enabled,@createUserid,@createTime) ");

                            sqlList.Add(SqlStringBuilder.ToString());

                            StringBuilder customerStringBuilder = new StringBuilder(1024);
                            customerStringBuilder.Append("select * from sys_customer (nolock) where customer_code='" + sapPtcpt.Kunnr + "'");//客户信息
                            List<SysCustomer> sysCustomers = dbConn.Query<SysCustomer>(customerStringBuilder.ToString()).ToList();

                            parameters = new DynamicParameters();
                            if (sysCustomers.Count == 0)
                            {
                                parameters.Add("@customerId", 0);//客户id
                            }
                            else
                            {
                                parameters.Add("@customerId", sysCustomers[0].CustomerId);//客户id
                            }
                            parameters.Add("@customerCode", sapPtcpt.Kunnr);//客户编码
                            if (sysPart.Count == 0)
                            {
                                parameters.Add("@partId", 0);//物料ID
                            }
                            else
                            {
                                parameters.Add("@partId", sysPart[0].PartId);//物料ID
                            }
                            parameters.Add("@partNo", sapPtcpt.Matnr);//物料代码
                            parameters.Add("@custPartNo", sapPtcpt.Kdmat);//客户零件号

                            parameters.Add("@factoryId", sysFactory[k].FactoryId);//工厂ID
                            parameters.Add("@factoryCode", sysFactory[k].FactoryCode);//工厂代码

                            parameters.Add("@enabled", 'Y');//启用
                            parameters.Add("@createUserid", 0);//创建人
                            parameters.Add("@createTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));//创建日期
                            parametersList.Add(parameters);


                            SqlStringBuilder = new StringBuilder(1024);
                            SqlStringBuilder.Append("update SAP_PTCPT set SYNFLG='Y',SYNTIM=@SYNTIM  where GUID=@GUID ");//更新同步状态
                            sqlList.Add(SqlStringBuilder.ToString());

                            parameters = new DynamicParameters();
                            parameters.Add("@GUID", sapPtcpt.Guid);//ID
                            parameters.Add("@SYNTIM", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));//同步时间
                            parametersList.Add(parameters);
                        }

                        bool staResult = ExecuteTransaction(sqlList, parametersList);
                        if (staResult == false)
                        {
                            sqlList = new List<string>();
                            parametersList = new List<DynamicParameters>();
                            SqlStringBuilder = new StringBuilder(1024);
                            SqlStringBuilder.Append("update SAP_PTCPT set SYNFLG='E',ERRMSG=@ERRMSG,SYNTIM=@SYNTIM  where GUID=@GUID ");//更新同步状态
                            sqlList.Add(SqlStringBuilder.ToString());

                            parameters = new DynamicParameters();
                            parameters.Add("@GUID", sapPtcpt.Guid);//ID
                            parameters.Add("@ERRMSG", "同步错误，请检查接口数据！");//错误
                            parameters.Add("@SYNTIM", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));//同步时间
                            parametersList.Add(parameters);
                            ExecuteTransaction(sqlList, parametersList);
                            return false;
                        }
                    }
                }
                return true;
            }
        }

        /// <summary>
        /// 获取MBOM同步到WMS系统
        /// </summary>
        /// <returns></returns>
        public List<SapBom_Extend> GetBomMasterInfo()
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                StringBuilder sql = new StringBuilder(1024);
                sql.Append("SELECT top 5000 * FROM sap_bom (nolock) ");
                sql.Append("WHERE  SYNFLG = 'N' ");
                sql.Append("ORDER BY RECTIM  ");

                return dbConn.Query<SapBom_Extend>(sql.ToString()).ToList();
            }
        }

        /// <summary>
        /// 添加MBOM同步到WMS系统
        /// </summary>
        /// <param name="sapPtcpt"></param>
        /// <returns></returns>
        public bool InsertBomMasterInfo(List<SapBom_Extend> sapBoms)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {

                List<string> sqlList = new List<string>();
                List<DynamicParameters> parametersList = new List<DynamicParameters>();

                StringBuilder SqlStringBuilder = new StringBuilder(1024);
                DynamicParameters parameters = new DynamicParameters();
                for (int i = 0; i < sapBoms.Count; i++)
                {

                    SapBom_Extend sapBom = sapBoms[i];

                    StringBuilder factoryStringBuilder = new StringBuilder(1024);
                    factoryStringBuilder.Append("select * from sys_factory (nolock) where factory_code='" + sapBom.Werks + "'");//工厂代码获取工厂ID
                    SysFactory sysFactory = dbConn.Query<SysFactory>(factoryStringBuilder.ToString()).FirstOrDefault();

                    StringBuilder partNoStringBuilder = new StringBuilder(1024);
                    partNoStringBuilder.Append("select * from sys_part (nolock) where part_no='" + sapBom.Matnr + "'");//零件号ID
                    List<SysPart> sysPart = dbConn.Query<SysPart>(partNoStringBuilder.ToString()).ToList();

                    string guidStr = Guid.NewGuid().ToString();

                    sqlList = new List<string>();
                    parametersList = new List<DynamicParameters>();
                    StringBuilder stringBuilder = new StringBuilder();
                    stringBuilder.Append(" SELECT * from sys_bom (nolock) WHERE part_no='" + sapBom.Matnr + "'");
                    List<SapBom> boms = dbConn.Query<SapBom>(stringBuilder.ToString()).ToList();
                    if (boms.Count > 0)
                    {
                        SqlStringBuilder = new StringBuilder(1024);
                        SqlStringBuilder.Append("UPDATE dbo.sys_bom ");
                        SqlStringBuilder.Append("   SET part_id = @partId,part_no = @partNo,bom_type = @bomType ");
                        SqlStringBuilder.Append("   ,unit = @unit,version = @version,remark = @remark ");
                        SqlStringBuilder.Append("   ,start_ymd = @startYmd,end_ymd = @endYmd,factory_id = @factoryId ");
                        SqlStringBuilder.Append("   ,factory_code = @factoryCode,enabled = @enabled,update_userid = @updateUserid ");
                        SqlStringBuilder.Append("   ,update_time = @updateTime ");
                        SqlStringBuilder.Append(" WHERE part_no = @partNo ");
                        sqlList.Add(SqlStringBuilder.ToString());
                        parameters = new DynamicParameters();
                        if (sysPart.Count == 0)
                        {
                            parameters.Add("@partId", 0);//物料ID
                        }
                        else
                        {
                            parameters.Add("@partId", sysPart[0].PartId);//物料ID
                        }
                        parameters.Add("@partNo", sapBom.Matnr);//物料编码
                        parameters.Add("@bomType", MesEnumUtil.BomType.REPORT);//bom类型  默认回冲
                        parameters.Add("@unit", sapBom.Meins);//单位
                        parameters.Add("@version", sapBom.Aennr);//ECN号
                        parameters.Add("@remark", sapBom.Matnr);//
                        parameters.Add("@startYmd", sapBom.Datuv);//生效日期
                        parameters.Add("@endYmd", sapBom.Datus);//失效日期
                        parameters.Add("@factoryId", sysFactory == null ? 0 : sysFactory.FactoryId);//工厂ID
                        parameters.Add("@factoryCode", sapBom.Werks);//工厂代码
                        parameters.Add("@enabled", 'Y');//启用
                        parameters.Add("@updateUserid", 0);//更新人
                        parameters.Add("@updateTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));//更新日期
                        parametersList.Add(parameters);

                        if (this.ExecuteTransaction(sqlList, parametersList))
                        {
                            sqlList = new List<string>();
                            parametersList = new List<DynamicParameters>();
                            SqlStringBuilder = new StringBuilder(1024);
                            SqlStringBuilder.Append("select * from sys_bom (nolock) where part_no='" + sapBom.Matnr + "' ");
                            List<SysBom> sysBom = dbConn.Query<SysBom>(SqlStringBuilder.ToString()).ToList();

                            SqlStringBuilder = new StringBuilder(1024);
                            SqlStringBuilder.Append("select * from sys_bom_detail (nolock) where part_no='" + sapBom.Matnr + "' and item_part_no='" + sapBom.Idnrk + "' ");
                            List<SysBomDetail> sysBomDetails = dbConn.Query<SysBomDetail>(SqlStringBuilder.ToString()).ToList();
                            if (sysBomDetails.Count > 0)
                            {
                                SqlStringBuilder = new StringBuilder(1024);
                                SqlStringBuilder.Append("UPDATE dbo.sys_bom_detail ");
                                SqlStringBuilder.Append("   SET part_id = @partId,part_no = @partNo ");
                                SqlStringBuilder.Append("      ,unit = @unit,qty = @qty ");
                                SqlStringBuilder.Append("      ,item_part_id = @itemPartId,item_part_no = @itemPartNo ");
                                SqlStringBuilder.Append("      ,item_qty = @itemQty,item_unit = @itemUnit ");
                                SqlStringBuilder.Append("      ,version = @version  ");
                                SqlStringBuilder.Append("      ,factory_id = @factoryId,factory_code = @factoryCode ");
                                SqlStringBuilder.Append("      ,enabled = @enabled,update_userid = @updateUserid ");
                                SqlStringBuilder.Append("      ,update_time = @updateTime ");
                                SqlStringBuilder.Append("      ,deliverymodel=@deliverymodel,whetherskip=@whetherskip");
                                SqlStringBuilder.Append("      ,attritionrate=@attritionrate,defaultwarehouse=@defaultwarehouse");
                                SqlStringBuilder.Append("      ,procedurecode=@procedurecode,outidentity=@outidentity ");
                                SqlStringBuilder.Append(" WHERE part_no = @partNo  and item_part_no=@itemPartNo ");

                                sqlList.Add(SqlStringBuilder.ToString());

                                partNoStringBuilder = new StringBuilder(1024);
                                partNoStringBuilder.Append("select * from sys_part (nolock) where part_no='" + sapBom.Idnrk + "'");//子零件号ID
                                List<SysPart> sysPartItem = dbConn.Query<SysPart>(partNoStringBuilder.ToString()).ToList();

                                parameters = new DynamicParameters();

                                if (sysPart.Count == 0)
                                {
                                    parameters.Add("@partId", 0);//物料Id
                                }
                                else
                                {
                                    parameters.Add("@partId", sysPart[0].PartId);//物料Id
                                }

                                parameters.Add("@partNo", sapBom.Matnr);//物料编码
                                parameters.Add("@unit", sapBom.Meins);//单位
                                parameters.Add("@qty", sapBom.Bmeng);//单位用量
                                if (sysPartItem.Count == 0)
                                {
                                    parameters.Add("@itemPartId", 0);//子件物料码Id
                                }
                                else
                                {
                                    parameters.Add("@itemPartId", sysPartItem[0].PartId);//子件物料码Id
                                }
                                parameters.Add("@itemPartNo", sapBom.Idnrk);//子件物料码
                                parameters.Add("@itemQty", sapBom.Menge);//单位用量
                                parameters.Add("@itemUnit", sapBom.Meins);//单位
                                parameters.Add("@version", sapBom.Aennr);//ECN号
                                parameters.Add("@factoryId", sysFactory == null ? 0 : sysFactory.FactoryId);//工厂ID
                                parameters.Add("@factoryCode", sapBom.Werks);//工厂代码
                                parameters.Add("@enabled", 'Y');//启用
                                parameters.Add("@updateUserid", 0);//修改人
                                parameters.Add("@updateTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));//修改日期
                                parameters.Add("@deliverymodel", sapBom.Deliverymodel);
                                parameters.Add("@whetherskip", sapBom.Whetherskip);
                                parameters.Add("@attritionrate", sapBom.Attritionrate);
                                parameters.Add("@defaultwarehouse", sapBom.Defaultwarehouse);
                                parameters.Add("@procedurecode", sapBom.Procedurecode);
                                parameters.Add("@outidentity", sapBom.Outidentity);
                                parametersList.Add(parameters);

                                SqlStringBuilder = new StringBuilder(1024);
                                SqlStringBuilder.Append("update SAP_BOM set SYNFLG='Y',SYNTIM=@SYNTIM  where GUID=@GUID ");//更新同步状态
                                sqlList.Add(SqlStringBuilder.ToString());

                                parameters = new DynamicParameters();
                                parameters.Add("@GUID", sapBom.Guid);//ID
                                parameters.Add("@SYNTIM", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));//同步时间
                                parametersList.Add(parameters);
                            }
                            else
                            {
                                SqlStringBuilder = new StringBuilder(1024);
                                SqlStringBuilder.Append("INSERT INTO dbo.sys_bom_detail(bom_id,part_id,part_no,unit,qty,item_part_id ");
                                SqlStringBuilder.Append("           ,item_part_no,item_qty,item_unit,factory_id,factory_code,enabled ");
                                SqlStringBuilder.Append("           ,create_userid,create_time ");
                                SqlStringBuilder.Append("           ,deliverymodel,whetherskip,attritionrate,defaultwarehouse,procedurecode,outidentity)");
                                SqlStringBuilder.Append("     VALUES(@bomId,@partId,@partNo,@unit,@qty,@itemPartId,@itemPartNo,@itemQty ");
                                SqlStringBuilder.Append("           ,@itemUnit,@factoryId,@factoryCode,@enabled,@createUserid,@createTime ");
                                SqlStringBuilder.Append("           ,@deliverymodel,@whetherskip,@attritionrate,@defaultwarehouse,@procedurecode,@outidentity)");
                                sqlList.Add(SqlStringBuilder.ToString());

                                partNoStringBuilder = new StringBuilder(1024);
                                partNoStringBuilder.Append("select * from sys_part (nolock) where part_no='" + sapBom.Idnrk + "'");//子零件号ID
                                List<SysPart> sysPartItem = dbConn.Query<SysPart>(partNoStringBuilder.ToString()).ToList();

                                parameters = new DynamicParameters();
                                parameters.Add("@bomId", sysBom[0].BomId);//BomId
                                if (sysPart.Count == 0)
                                {
                                    parameters.Add("@partId", 0);//物料Id
                                }
                                else
                                {
                                    parameters.Add("@partId", sysPart[0].PartId);//物料Id
                                }

                                parameters.Add("@partNo", sapBom.Matnr);//物料编码
                                parameters.Add("@unit", sapBom.Meins);//单位
                                parameters.Add("@qty", sapBom.Bmeng);//单位用量
                                if (sysPartItem.Count == 0)
                                {
                                    parameters.Add("@itemPartId", 0);//子件物料码Id
                                }
                                else
                                {
                                    parameters.Add("@itemPartId", sysPartItem[0].PartId);//子件物料码Id
                                }
                                parameters.Add("@itemPartNo", sapBom.Idnrk);//子件物料码
                                parameters.Add("@itemQty", sapBom.Menge);//单位用量
                                parameters.Add("@itemUnit", sapBom.Meins);//单位
                                parameters.Add("@factoryId", sysFactory == null ? 0 : sysFactory.FactoryId);//工厂ID
                                parameters.Add("@factoryCode", sapBom.Werks);//工厂代码
                                parameters.Add("@enabled", 'Y');//启用
                                parameters.Add("@createUserid", 0);//创建人
                                parameters.Add("@createTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));//创建日期
                                parameters.Add("@deliverymodel", sapBom.Deliverymodel);
                                parameters.Add("@whetherskip", sapBom.Whetherskip);
                                parameters.Add("@attritionrate", sapBom.Attritionrate);
                                parameters.Add("@defaultwarehouse", sapBom.Defaultwarehouse);
                                parameters.Add("@procedurecode", sapBom.Procedurecode);
                                parameters.Add("@outidentity", sapBom.Outidentity);
                                parametersList.Add(parameters);

                                SqlStringBuilder = new StringBuilder(1024);
                                SqlStringBuilder.Append("update SAP_BOM set SYNFLG='Y',SYNTIM=@SYNTIM  where GUID=@GUID ");//更新同步状态
                                sqlList.Add(SqlStringBuilder.ToString());

                                parameters = new DynamicParameters();
                                parameters.Add("@GUID", sapBom.Guid);//ID
                                parameters.Add("@SYNTIM", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));//同步时间
                                parametersList.Add(parameters);
                            }

                        }
                        else
                        {
                            sqlList = new List<string>();
                            parametersList = new List<DynamicParameters>();
                            SqlStringBuilder = new StringBuilder(1024);
                            SqlStringBuilder.Append("update SAP_BOM set SYNFLG='E',ERRMSG=@ERRMSG,SYNTIM=@SYNTIM  where GUID=@GUID ");//更新同步状态
                            sqlList.Add(SqlStringBuilder.ToString());

                            parameters = new DynamicParameters();
                            parameters.Add("@GUID", sapBom.Guid);//ID
                            parameters.Add("@ERRMSG", "同步错误，请检查接口数据！");//错误
                            parameters.Add("@SYNTIM", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));//同步时间
                            parametersList.Add(parameters);
                            ExecuteTransaction(sqlList, parametersList);

                            return false;
                        }

                    }
                    else
                    {
                        SqlStringBuilder = new StringBuilder(1024);
                        SqlStringBuilder.Append("INSERT INTO dbo.sys_bom(part_id,part_no,bom_type,unit,version,remark,start_ymd ");
                        SqlStringBuilder.Append("           ,end_ymd,factory_id,factory_code,enabled,create_userid,create_time,guid) ");
                        SqlStringBuilder.Append("     VALUES(@partId,@partNo,@bomType,@unit,@version,@remark,@startYmd,@endYmd ");
                        SqlStringBuilder.Append("           ,@factoryId,@factoryCode,@enabled,@createUserid,@createTime,@guid) ");
                        sqlList.Add(SqlStringBuilder.ToString());

                        parameters = new DynamicParameters();
                        if (sysPart.Count == 0)
                        {
                            parameters.Add("@partId", 0);//物料ID
                        }
                        else
                        {
                            parameters.Add("@partId", sysPart[0].PartId);//物料ID
                        }
                        parameters.Add("@partNo", sapBom.Matnr);//物料编码
                        parameters.Add("@bomType", MesEnumUtil.BomType.REPORT);//bom类型 默认回冲
                        parameters.Add("@unit", sapBom.Meins);//单位
                        parameters.Add("@version", sapBom.Aennr);//ECN号
                        parameters.Add("@remark", sapBom.Matnr);//
                        parameters.Add("@startYmd", sapBom.Datuv);//生效日期
                        parameters.Add("@endYmd", sapBom.Datus);//失效日期
                        parameters.Add("@factoryId", sysFactory == null ? 0 : sysFactory.FactoryId);//工厂ID
                        parameters.Add("@factoryCode", sapBom.Werks);//工厂代码
                        parameters.Add("@enabled", 'Y');//启用
                        parameters.Add("@createUserid", 0);//创建人
                        parameters.Add("@createTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));//创建日期
                        parameters.Add("@guid", guidStr);//guid
                        parametersList.Add(parameters);

                        if (this.ExecuteTransaction(sqlList, parametersList))
                        {
                            sqlList = new List<string>();
                            parametersList = new List<DynamicParameters>();
                            SqlStringBuilder = new StringBuilder(1024);
                            SqlStringBuilder.Append("select * from sys_bom (nolock) where part_no='" + sapBom.Matnr + "' ");
                            List<SysBom> sysBom = dbConn.Query<SysBom>(SqlStringBuilder.ToString()).ToList();

                            SqlStringBuilder = new StringBuilder(1024);
                            SqlStringBuilder.Append("INSERT INTO dbo.sys_bom_detail(bom_id,part_id,part_no,unit,qty,item_part_id ");
                            SqlStringBuilder.Append("           ,item_part_no,item_qty,item_unit,factory_id,factory_code,enabled ");
                            SqlStringBuilder.Append("           ,create_userid,create_time ");
                            SqlStringBuilder.Append("           ,deliverymodel,whetherskip,attritionrate,defaultwarehouse,procedurecode,outidentity)");
                            SqlStringBuilder.Append("     VALUES(@bomId,@partId,@partNo,@unit,@qty,@itemPartId,@itemPartNo,@itemQty ");
                            SqlStringBuilder.Append("           ,@itemUnit,@factoryId,@factoryCode,@enabled,@createUserid,@createTime ");
                            SqlStringBuilder.Append("           ,@deliverymodel,@whetherskip,@attritionrate,@defaultwarehouse,@procedurecode,@outidentity)");

                            sqlList.Add(SqlStringBuilder.ToString());

                            partNoStringBuilder = new StringBuilder(1024);
                            partNoStringBuilder.Append("select * from sys_part (nolock) where part_no='" + sapBom.Idnrk + "'");//子零件号ID
                            List<SysPart> sysPartItem = dbConn.Query<SysPart>(partNoStringBuilder.ToString()).ToList();

                            parameters = new DynamicParameters();
                            parameters.Add("@bomId", sysBom[0].BomId);//BomId
                            if (sysPart.Count == 0)
                            {
                                parameters.Add("@partId", 0);//物料Id
                            }
                            else
                            {
                                parameters.Add("@partId", sysPart[0].PartId);//物料Id
                            }

                            parameters.Add("@partNo", sapBom.Matnr);//物料编码
                            parameters.Add("@unit", sapBom.Meins);//单位
                            parameters.Add("@qty", sapBom.Bmeng);//单位用量
                            if (sysPartItem.Count == 0)
                            {
                                parameters.Add("@itemPartId", 0);//子件物料码Id
                            }
                            else
                            {
                                parameters.Add("@itemPartId", sysPartItem[0].PartId);//子件物料码Id
                            }
                            parameters.Add("@itemPartNo", sapBom.Idnrk);//子件物料码
                            parameters.Add("@itemQty", sapBom.Menge);//单位用量
                            parameters.Add("@itemUnit", sapBom.Meins);//单位
                            parameters.Add("@factoryId", sysFactory == null ? 0 : sysFactory.FactoryId);//工厂ID
                            parameters.Add("@factoryCode", sapBom.Werks);//工厂代码
                            parameters.Add("@enabled", 'Y');//启用
                            parameters.Add("@createUserid", 0);//创建人
                            parameters.Add("@createTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));//创建日期
                            parameters.Add("@deliverymodel", sapBom.Deliverymodel);
                            parameters.Add("@whetherskip", sapBom.Whetherskip);
                            parameters.Add("@attritionrate", sapBom.Attritionrate);
                            parameters.Add("@defaultwarehouse", sapBom.Defaultwarehouse);
                            parameters.Add("@procedurecode", sapBom.Procedurecode);
                            parameters.Add("@outidentity", sapBom.Outidentity);
                            parametersList.Add(parameters);

                            SqlStringBuilder = new StringBuilder(1024);
                            SqlStringBuilder.Append("update SAP_BOM set SYNFLG='Y',SYNTIM=@SYNTIM  where GUID=@GUID ");//更新同步状态
                            sqlList.Add(SqlStringBuilder.ToString());

                            parameters = new DynamicParameters();
                            parameters.Add("@GUID", sapBom.Guid);//ID
                            parameters.Add("@SYNTIM", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));//同步时间
                            parametersList.Add(parameters);
                        }
                        else
                        {
                            sqlList = new List<string>();
                            parametersList = new List<DynamicParameters>();
                            SqlStringBuilder = new StringBuilder(1024);
                            SqlStringBuilder.Append("update SAP_BOM set SYNFLG='E',ERRMSG=@ERRMSG,SYNTIM=@SYNTIM  where GUID=@GUID ");//更新同步状态
                            sqlList.Add(SqlStringBuilder.ToString());

                            parameters = new DynamicParameters();
                            parameters.Add("@GUID", sapBom.Guid);//ID
                            parameters.Add("@ERRMSG", "同步错误，请检查接口数据！");//错误
                            parameters.Add("@SYNTIM", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));//同步时间
                            parametersList.Add(parameters);
                            ExecuteTransaction(sqlList, parametersList);
                            return false;
                        }
                    }

                    bool staResult = ExecuteTransaction(sqlList, parametersList);
                    if (staResult == false)
                    {
                        sqlList = new List<string>();
                        parametersList = new List<DynamicParameters>();
                        SqlStringBuilder = new StringBuilder(1024);
                        SqlStringBuilder.Append("update SAP_BOM set SYNFLG='E',ERRMSG=@ERRMSG,SYNTIM=@SYNTIM  where GUID=@GUID ");//更新同步状态
                        sqlList.Add(SqlStringBuilder.ToString());

                        parameters = new DynamicParameters();
                        parameters.Add("@GUID", sapBom.Guid);//ID
                        parameters.Add("@ERRMSG", "同步错误，请检查接口数据！");//错误
                        parameters.Add("@SYNTIM", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));//同步时间
                        parametersList.Add(parameters);
                        ExecuteTransaction(sqlList, parametersList);
                        return false;
                    }
                }
                return true;
            }
        }

        

        #endregion

        #region 采购收货
        /// <summary>
        /// SAP系统把ASN传递到WMS用于采购收货
        /// </summary>
        /// <returns></returns>
        public List<SapAsn> GetASNDataInfo()
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                StringBuilder sql = new StringBuilder(1024);
                sql.Append("SELECT TOP 1000 ZASNNO, COUNT(1), ZDATE,SID FROM sap_asn (nolock) ");
                sql.Append("WHERE SYNFLG = 'N' ");
                sql.Append("GROUP BY ZDATE,ZASNNO,SID ");
                sql.Append("ORDER BY ZDATE ");
                return dbConn.Query<SapAsn>(sql.ToString()).ToList();
            }
        }

        /// <summary>
        /// 添加SAP系统把ASN传递到WMS用于采购收货
        /// </summary>
        /// <param name="sapCu"></param>
        /// <returns></returns>
        public bool InsertASNDataInfo(List<SapAsn> sapAsns)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                dbConn.Open();
                StringBuilder SqlStringBuilder = new StringBuilder(1024);
                DynamicParameters parameters = new DynamicParameters();

                StringBuilder factoryStringBuilder = new StringBuilder(1024);
                factoryStringBuilder.Append("select * from sys_factory (nolock) where enabled='Y'");//工厂
                List<SysFactory> sysFactoryAll = dbConn.Query<SysFactory>(factoryStringBuilder.ToString()).ToList();

                StringBuilder vendorStringBuilder = new StringBuilder(1024);
                vendorStringBuilder.Append("select * from sys_vendor (nolock) where enabled='Y'");//供应商信息
                List<SysVendor> sysVendorAll = dbConn.Query<SysVendor>(vendorStringBuilder.ToString()).ToList();

                StringBuilder partNoStringBuilder = new StringBuilder(1024);
                partNoStringBuilder.Append("select * from sys_part (nolock) where enabled='Y' ");//零件号
                List<SysPart> sysPartAll = dbConn.Query<SysPart>(partNoStringBuilder.ToString()).ToList();

                for (int s = 0; s < sapAsns.Count; s++)
                {
                    SqlStringBuilder = new StringBuilder(1024);
                    SqlStringBuilder.Append("SELECT * FROM sap_asn (nolock) ");
                    SqlStringBuilder.Append("WHERE ZASNNO ='" + sapAsns[s].Zasnno + "' AND SID='" + sapAsns[s].Sid + "' ");
                    List<SapAsn> saps = dbConn.Query<SapAsn>(SqlStringBuilder.ToString()).ToList();

                    SqlStringBuilder = new StringBuilder(1024);
                    SqlStringBuilder.Append("SELECT * FROM sys_stock (nolock) ");
                    SqlStringBuilder.Append("WHERE ref_order_no = '" + sapAsns[s].Zasnno + "'");
                    List<SysStock> stocksList = dbConn.Query<SysStock>(SqlStringBuilder.ToString()).ToList();

                    List<string> sqlList = new List<string>();
                    List<DynamicParameters> parametersList = new List<DynamicParameters>();

                    foreach (SapAsn sapAsn in saps)
                    {
                        if (sapAsn.Zstas != "X")//其他状态
                        {
                            SysFactory sysFactory = sysFactoryAll.Where(a => a.FactoryCode == sapAsn.Werks).FirstOrDefault();//工厂
                            SysVendor sysVendor = sysVendorAll.Where(a => a.VendorCode == sapAsn.Lifnr).FirstOrDefault();//供应商信息
                            SysPart sysPart = sysPartAll.Where(a => a.PartNo == sapAsn.Matnr).FirstOrDefault();//零件号ID

                            //SN
                            int qty = Convert.ToInt32(sapAsn.ZcnNum);
                            int vendorId = sysVendor == null ? 0 : sysVendor.VendorId;//供应商代码
                            string vendorCode = sysVendor == null ? "" : sysVendor.VendorCode;//供应商代码

                            int partId = 0;
                            string partNo = "";
                            string partSpec = "";
                            decimal defaultBoxQty = 0;
                            if (sysPart != null)
                            {
                                partId = sysPart.PartId;
                                partNo = sysPart.PartNo;
                                partSpec = sysPart.PartSpec;
                                defaultBoxQty = Convert.ToInt32(sysPart.DefaultBoxQty == null ? 0 : sysPart.DefaultBoxQty);
                            }
                            string unit = sapAsn.Unit;//单位

                            string orderNo_New = sapAsn.Zasnno;
                            string carNo_New = sapAsn.Ztxm;

                            SysStock stock = stocksList.Where(a => a.CartonNo == sapAsn.Ztxm).FirstOrDefault();
                            if (stock != null)
                            {
                                SqlStringBuilder = new StringBuilder(1024);
                                SqlStringBuilder.Append("UPDATE dbo.sys_stock ");
                                SqlStringBuilder.Append("   SET vendor_id = @vendorId,vendor_code = @vendorCode ");
                                SqlStringBuilder.Append("      ,part_id = @partId,part_no = @partNo,part_spec = @partSpec ");
                                SqlStringBuilder.Append("      ,lot_no = @lotNo,qty = @qty,snp_qty = @snpQty ");
                                SqlStringBuilder.Append("      ,erp_warehouse = @erpWarehouse ,ref_order_no = @refOrderNo ");
                                SqlStringBuilder.Append("      ,unit = @unit,factory_id = @factoryId ");
                                SqlStringBuilder.Append("      ,factory_code = @factoryCode,enabled = @enabled ");
                                SqlStringBuilder.Append("      ,update_userid = @updateUserid,update_time = @updateTime ");
                                SqlStringBuilder.Append(" WHERE carton_no = @cartonNo ");

                                DynamicParameters param3 = new DynamicParameters();
                                param3.Add("@vendorId", vendorId);
                                param3.Add("@vendorCode", vendorCode);
                                param3.Add("@cartonNo", carNo_New);
                                param3.Add("@partId", partId);
                                param3.Add("@partNo", sapAsn.Matnr);
                                param3.Add("@partSpec", partSpec);
                                param3.Add("@lotNo", DateTime.Now.ToString("yyyyMMdd"));
                                param3.Add("@qty", qty);
                                param3.Add("@snpQty", defaultBoxQty);
                                param3.Add("@erpWarehouse", sapAsn.Lgort);//库存地
                                param3.Add("@refOrderNo", orderNo_New);
                                param3.Add("@unit", unit);
                                param3.Add("@factoryId", sysFactory == null ? 0 : sysFactory.FactoryId);//工厂ID
                                param3.Add("@factoryCode", sapAsn.Werks);//工厂代码
                                param3.Add("@updateUserid", 0);//修改人
                                param3.Add("@updateTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));//修改日期
                                param3.Add("@enabled", "Y");

                                sqlList.Add(SqlStringBuilder.ToString());
                                parametersList.Add(param3);
                            }
                            else
                            {
                                SqlStringBuilder.Remove(0, SqlStringBuilder.Length);
                                SqlStringBuilder.Append("INSERT INTO dbo.sys_stock (vendor_id,vendor_code,carton_no,part_id,part_no,part_spec ");
                                SqlStringBuilder.Append("           ,lot_no,status,qty,snp_qty ");
                                SqlStringBuilder.Append("           ,erp_warehouse,ref_order_no,unit,factory_id ");
                                SqlStringBuilder.Append("           ,factory_code,enabled,create_userid,create_time) ");
                                SqlStringBuilder.Append("     VALUES (@vendorId,@vendorCode,@cartonNo,@partId,@partNo,@partSpec ");
                                SqlStringBuilder.Append("           ,@lotNo,@status,@qty,@snpQty,@erpWarehouse,@refOrderNo,@unit");
                                SqlStringBuilder.Append("           ,@factoryId,@factoryCode,@enabled,@createUserid ");
                                SqlStringBuilder.Append("           ,CONVERT(varchar(50), GETDATE(), 21)) ");

                                DynamicParameters param3 = new DynamicParameters();
                                param3.Add("@vendorId", vendorId);
                                param3.Add("@vendorCode", vendorCode);
                                param3.Add("@cartonNo", carNo_New);
                                param3.Add("@partId", partId);
                                param3.Add("@partNo", sapAsn.Matnr);
                                param3.Add("@partSpec", partSpec);
                                param3.Add("@lotNo", DateTime.Now.ToString("yyyyMMdd"));
                                param3.Add("@status", "20");
                                param3.Add("@qty", qty);
                                param3.Add("@snpQty", defaultBoxQty);
                                param3.Add("@erpWarehouse", sapAsn.Lgort);//库存地
                                param3.Add("@refOrderNo", orderNo_New);
                                param3.Add("@unit", unit);
                                param3.Add("@factoryId", sysFactory == null ? 0 : sysFactory.FactoryId);//工厂ID
                                param3.Add("@factoryCode", sapAsn.Werks);//工厂代码
                                param3.Add("@enabled", "Y");
                                param3.Add("@createUserid", 0);

                                sqlList.Add(SqlStringBuilder.ToString());
                                parametersList.Add(param3);
                            }
                        }
                        else
                        {
                            SqlStringBuilder = new StringBuilder(1024);
                            SqlStringBuilder.Append("UPDATE dbo.sys_stock ");
                            SqlStringBuilder.Append("   SET enabled = @enabled ");
                            SqlStringBuilder.Append("      ,update_userid = @updateUserid,update_time = @updateTime ");
                            SqlStringBuilder.Append(" WHERE carton_no = @cartonNo ");
                            DynamicParameters param3 = new DynamicParameters();
                            string carNo_New = sapAsn.Ztxm;
                            param3.Add("@enabled", "N");
                            param3.Add("@updateUserid", "0");
                            param3.Add("@updateTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));//修改日期
                            param3.Add("@cartonNo", carNo_New);
                            sqlList.Add(SqlStringBuilder.ToString());
                            parametersList.Add(param3);
                        }
                    }

                    #region 明细
                    SqlStringBuilder = new StringBuilder(1024);
                    SqlStringBuilder.Append("SELECT * FROM wms_purchase_detail (nolock) ");
                    SqlStringBuilder.Append("WHERE order_no = '" + sapAsns[s].Zasnno + "'");
                    List<WmsPurchaseDetail> wmsPurchaseDetailsList = dbConn.Query<WmsPurchaseDetail>(SqlStringBuilder.ToString()).ToList();

                    SqlStringBuilder = new StringBuilder(1024);
                    SqlStringBuilder.Append("SELECT ZASNNO,LIFNR,ZRNUM,MATNR,SUM(ZCN_NUM) SumZcnNum,COUNT(1) BoxQty,UNIT,PSTYP,ZDATE,ZCJSJ,WERKS,LGORT FROM SAP_ASN (nolock) WHERE ZASNNO='" + sapAsns[s].Zasnno + "' AND SID ='" + sapAsns[s].Sid + "' AND Zstas='X' ");
                    SqlStringBuilder.Append("	GROUP BY ZASNNO,LIFNR,ZRNUM,MATNR,UNIT,PSTYP,ZDATE,ZCJSJ,WERKS,LGORT  ");
                    List<SapAsn> sapAsnsDetailsDel = dbConn.Query<SapAsn>(SqlStringBuilder.ToString()).ToList();
                    //单据明细
                    foreach (SapAsn sapAsnsDetail in sapAsnsDetailsDel)
                    {
                        WmsPurchaseDetail wmsPurchaseDetailInfo = wmsPurchaseDetailsList.Where(a => a.OrderNo == sapAsnsDetail.Zasnno && a.PartNo == sapAsnsDetail.Matnr).FirstOrDefault();
                        if (wmsPurchaseDetailInfo != null)
                        {
                            SqlStringBuilder = new StringBuilder(1024);
                            SqlStringBuilder.Append("UPDATE dbo.wms_purchase_detail ");
                            SqlStringBuilder.Append("   SET part_no = @partNo,item_status=@itemStatus ");
                            SqlStringBuilder.Append("      ,update_userid = @updateUserid,update_time = @updateTime ");
                            SqlStringBuilder.Append(" WHERE order_no = @orderNo and part_no=@partNo ");

                            sqlList.Add(SqlStringBuilder.ToString());

                            parameters = new DynamicParameters();
                            parameters.Add("@orderNo", sapAsnsDetail.Zasnno);//ASN号
                            parameters.Add("@partNo", sapAsnsDetail.Matnr);//物料编码
                            parameters.Add("@itemStatus", (int)WmsEnumUtil.PurchaseOrderDetailStatus.CANCEL);//状态 已取消
                            parameters.Add("@updateUserid", 0);//创建人
                            parameters.Add("@updateTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));//创建日期
                            parametersList.Add(parameters);
                        }
                    }

                    SqlStringBuilder = new StringBuilder(1024);
                    SqlStringBuilder.Append("SELECT ZASNNO,LIFNR,ZRNUM,MATNR,SUM(ZCN_NUM) SumZcnNum,COUNT(1) BoxQty,UNIT,PSTYP,ZDATE,ZCJSJ,WERKS,LGORT FROM SAP_ASN (nolock) WHERE ZASNNO='" + sapAsns[s].Zasnno + "' AND SID ='" + sapAsns[s].Sid + "' AND Zstas!='X' ");
                    SqlStringBuilder.Append("	GROUP BY ZASNNO,LIFNR,ZRNUM,MATNR,UNIT,PSTYP,ZDATE,ZCJSJ,WERKS,LGORT  ");
                    List<SapAsn> sapAsnsDetails = dbConn.Query<SapAsn>(SqlStringBuilder.ToString()).ToList();
                    //单据明细
                    foreach (SapAsn sapAsnsDetail in sapAsnsDetails)
                    {
                        WmsPurchaseDetail wmsPurchaseDetailInfo = wmsPurchaseDetailsList.Where(a => a.OrderNo == sapAsnsDetail.Zasnno && a.PartNo == sapAsnsDetail.Matnr).FirstOrDefault();
                        if (wmsPurchaseDetailInfo != null)
                        {
                            SqlStringBuilder = new StringBuilder(1024);
                            SqlStringBuilder.Append("UPDATE dbo.wms_purchase_detail ");
                            SqlStringBuilder.Append("   SET item_no = @itemNo,part_id = @partId ");
                            SqlStringBuilder.Append("      ,part_no = @partNo,part_spec = @partSpec ");
                            SqlStringBuilder.Append("      ,qty = @qty,box_qty=@boxQty,snp_qty=@snpQty,unit = @unit ");
                            SqlStringBuilder.Append("      ,erp_warehouse = @erpWarehouse,item_status = @itemStatus ");
                            SqlStringBuilder.Append("      ,factory_id = @factoryId,factory_code = @factoryCode ");
                            SqlStringBuilder.Append("      ,enabled = @enabled,update_userid = @updateUserid ");
                            SqlStringBuilder.Append("      ,update_time = @updateTime ");
                            SqlStringBuilder.Append(" WHERE order_no = @orderNo and part_no=@partNo ");

                            sqlList.Add(SqlStringBuilder.ToString());

                            parameters = new DynamicParameters();
                            parameters.Add("@orderNo", sapAsnsDetail.Zasnno);//ASN号
                            parameters.Add("@itemNo", sapAsnsDetail.Zrnum);//ASN item

                            List<SysPart> sysPart = sysPartAll.Where(a => a.PartNo == sapAsnsDetail.Matnr).ToList();//零件号ID
                            if (sysPart.Count == 0)
                            {
                                parameters.Add("@partId", 0);//物料Id
                                parameters.Add("@partSpec", "");//物料描述
                                parameters.Add("@snpQty", 0);//标准包装
                            }
                            else
                            {
                                parameters.Add("@partId", sysPart[0].PartId);//物料Id
                                parameters.Add("@partSpec", sysPart[0].PartSpec);//物料描述
                                parameters.Add("@snpQty", sysPart[0].DefaultBoxQty);//标准包装
                            }
                            parameters.Add("@partNo", sapAsnsDetail.Matnr);//物料编码

                            parameters.Add("@boxQty", sapAsnsDetail.BoxQty);//包装数量
                            parameters.Add("@qty", sapAsnsDetail.SumZcnNum);//数量

                            parameters.Add("@unit", sapAsnsDetail.Unit);//单位
                            parameters.Add("@erpWarehouse", sapAsnsDetail.Lgort);//库存地
                            parameters.Add("@itemStatus", (int)WmsEnumUtil.PurchaseOrderDetailStatus.GENERATED);//状态 已生成

                            SysFactory sysFactory = sysFactoryAll.Where(a => a.FactoryCode == sapAsnsDetail.Werks).FirstOrDefault();//工厂
                            parameters.Add("@factoryId", sysFactory == null ? 0 : sysFactory.FactoryId);//工厂ID

                            parameters.Add("@factoryCode", sapAsnsDetail.Werks);//工厂代码
                            parameters.Add("@enabled", 'Y');//启用
                            parameters.Add("@updateUserid", 0);//创建人
                            parameters.Add("@updateTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));//创建日期
                            parametersList.Add(parameters);
                        }
                        else
                        {
                            SqlStringBuilder = new StringBuilder(1024);
                            SqlStringBuilder.Append("INSERT INTO dbo.wms_purchase_detail(order_no,item_no,part_id,part_no,part_spec,qty,rec_qty,box_qty,rec_box_qty,snp_qty");
                            SqlStringBuilder.Append("           ,unit,erp_warehouse,item_status,factory_id,factory_code ");
                            SqlStringBuilder.Append("           ,enabled,create_userid,create_time) ");
                            SqlStringBuilder.Append("     VALUES(@orderNo,@itemNo,@partId,@partNo,@partSpec,@qty,0,@boxQty,0,@snpQty ");
                            SqlStringBuilder.Append("           ,@unit,@erpWarehouse,@itemStatus,@factoryId,@factoryCode,@enabled ");
                            SqlStringBuilder.Append("           ,@createUserid,@createTime) ");

                            sqlList.Add(SqlStringBuilder.ToString());

                            parameters = new DynamicParameters();
                            parameters.Add("@orderNo", sapAsnsDetail.Zasnno);//ASN号
                            parameters.Add("@itemNo", sapAsnsDetail.Zrnum);//ASN item

                            SysPart sysPart = sysPartAll.Where(a => a.PartNo == sapAsnsDetail.Matnr).FirstOrDefault();//零件号ID
                            if (sysPart == null)
                            {
                                parameters.Add("@partId", 0);//物料Id
                                parameters.Add("@partSpec", "");//物料描述
                                parameters.Add("@snpQty", 0);//标准包装
                            }
                            else
                            {
                                parameters.Add("@partId", sysPart.PartId);//物料Id
                                parameters.Add("@partSpec", sysPart.PartSpec);//物料描述
                                parameters.Add("@snpQty", sysPart.DefaultBoxQty);//标准包装
                            }
                            parameters.Add("@partNo", sapAsnsDetail.Matnr);//物料编码

                            parameters.Add("@boxQty", sapAsnsDetail.BoxQty);//包装数量
                            parameters.Add("@qty", sapAsnsDetail.SumZcnNum);//数量

                            parameters.Add("@unit", sapAsnsDetail.Unit);//单位
                            parameters.Add("@erpWarehouse", sapAsnsDetail.Lgort);//库存地
                            parameters.Add("@itemStatus", (int)WmsEnumUtil.PurchaseOrderDetailStatus.GENERATED);//状态 已生成

                            SysFactory sysFactory = sysFactoryAll.Where(a => a.FactoryCode == sapAsnsDetail.Werks).FirstOrDefault();//工厂
                            parameters.Add("@factoryId", sysFactory == null ? 0 : sysFactory.FactoryId);//工厂ID
                            parameters.Add("@factoryCode", sapAsnsDetail.Werks);//工厂代码
                            parameters.Add("@enabled", 'Y');//启用
                            parameters.Add("@createUserid", 0);//创建人
                            parameters.Add("@createTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));//创建日期
                            parametersList.Add(parameters);
                        }
                    }
                    #endregion

                    #region 主表

                    SqlStringBuilder = new StringBuilder(1024);
                    SqlStringBuilder.Append("SELECT * FROM wms_purchase (nolock) ");
                    SqlStringBuilder.Append("WHERE order_no = '" + sapAsns[s].Zasnno + "'");
                    List<WmsPurchase> wmsPurchasesList = dbConn.Query<WmsPurchase>(SqlStringBuilder.ToString()).ToList();
                    string guidStr = Guid.NewGuid().ToString();

                    SqlStringBuilder = new StringBuilder(1024);
                    SqlStringBuilder.Append("SELECT ZASNNO,LIFNR,ZRNUM,MATNR,ZCN_NUM,UNIT,PSTYP,ZDATE,ZCJSJ,WERKS,LGORT FROM SAP_ASN (nolock) WHERE ZASNNO='" + sapAsns[s].Zasnno + "' AND SID ='" + sapAsns[s].Sid + "' AND ZSTAS='X' ");
                    SapAsn sapAsnsmainDel = dbConn.Query<SapAsn>(SqlStringBuilder.ToString()).FirstOrDefault();

                    if (wmsPurchasesList.Count > 0)
                    {
                        if (sapAsnsmainDel != null)
                        {
                            SqlStringBuilder = new StringBuilder(1024);
                            SqlStringBuilder.Append("UPDATE dbo.wms_purchase ");
                            SqlStringBuilder.Append("   SET order_status = @orderStatus ");
                            SqlStringBuilder.Append("      ,update_userid = @updateUserid,update_time = @updateTime ");
                            SqlStringBuilder.Append(" WHERE order_no = @orderNo ");
                            sqlList.Add(SqlStringBuilder.ToString());

                            parameters = new DynamicParameters();
                            parameters.Add("@orderNo", sapAsnsmainDel.Zasnno);//ASN号
                            parameters.Add("@orderStatus", 60);//状态 已生成
                            parameters.Add("@updateUserid", 0);//更新人
                            parameters.Add("@updateTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));//更新日期
                            parametersList.Add(parameters);
                        }
                    }

                    SqlStringBuilder = new StringBuilder(1024);
                    SqlStringBuilder.Append("SELECT ZASNNO,LIFNR,ZRNUM,MATNR,ZCN_NUM,UNIT,PSTYP,ZDATE,ZCJSJ,WERKS,LGORT FROM SAP_ASN (nolock) WHERE ZASNNO='" + sapAsns[s].Zasnno + "' AND SID ='" + sapAsns[s].Sid + "' AND ZSTAS!='X' ");
                    SapAsn sapAsnsmain = dbConn.Query<SapAsn>(SqlStringBuilder.ToString()).FirstOrDefault();

                    if (sapAsnsmain != null)
                    {
                        if (wmsPurchasesList.Count > 0)
                        {
                            SqlStringBuilder = new StringBuilder(1024);
                            SqlStringBuilder.Append("UPDATE dbo.wms_purchase ");
                            SqlStringBuilder.Append("   SET order_type = @orderType,order_status = @orderStatus ");
                            SqlStringBuilder.Append("      ,vendor_id = @vendorId,vendor_code = @vendorCode,se_date = @seDate ");
                            SqlStringBuilder.Append("      ,se_time = @seTime,factory_id = @factoryId,factory_code = @factoryCode ");
                            SqlStringBuilder.Append("      ,enabled = @enabled,update_userid = @updateUserid,update_time = @updateTime,PSTYP=@PSTYP ");
                            SqlStringBuilder.Append(" WHERE order_no = @orderNo ");
                            sqlList.Add(SqlStringBuilder.ToString());

                            parameters = new DynamicParameters();
                            parameters.Add("@orderNo", sapAsnsmain.Zasnno);//ASN号
                            parameters.Add("@orderType", 20);//类型 ASN
                            parameters.Add("@orderStatus", 20);//状态 已生成
                            SysVendor sysVendor = sysVendorAll.Where(a => a.VendorCode == sapAsnsmain.Lifnr).FirstOrDefault();//供应商信息
                            parameters.Add("@vendorId", sysVendor == null ? 0 : sysVendor.VendorId);//供应商ID

                            parameters.Add("@vendorCode", sapAsnsmain.Lifnr);//供应商代码
                            parameters.Add("@seDate", sapAsnsmain.Zdate);//计划交货日期
                            parameters.Add("@seTime", sapAsnsmain.Zcjsj);//计划交货时间

                            SysFactory sysFactory = sysFactoryAll.Where(a => a.FactoryCode == sapAsnsmain.Werks).FirstOrDefault();//工厂
                            parameters.Add("@factoryId", sysFactory == null ? 0 : sysFactory.FactoryId);//工厂ID
                            parameters.Add("@factoryCode", sapAsnsmain.Werks);//工厂代码

                            parameters.Add("@PSTYP", sapAsnsmain.Pstyp);//采购标识0：标准，3：外协加工，2：寄售，1：限制，7：库存转存
                            parameters.Add("@enabled", 'Y');//启用
                            parameters.Add("@updateUserid", 0);//更新人
                            parameters.Add("@updateTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));//更新日期

                            parametersList.Add(parameters);
                        }
                        else
                        {
                            SqlStringBuilder = new StringBuilder(1024);
                            SqlStringBuilder.Append("INSERT INTO dbo.wms_purchase(order_no,order_type,order_status,vendor_id,vendor_code ");
                            SqlStringBuilder.Append("           ,se_date,se_time,factory_id,factory_code,enabled,create_userid,create_time,guid,PSTYP) ");
                            SqlStringBuilder.Append("     VALUES(@orderNo,@orderType,@orderStatus,@vendorId,@vendorCode,@seDate,@seTime ");
                            SqlStringBuilder.Append("           ,@factoryId,@factoryCode,@enabled,@createUserid,@createTime,@guid,@PSTYP) ");

                            sqlList.Add(SqlStringBuilder.ToString());

                            parameters = new DynamicParameters();
                            parameters.Add("@orderNo", sapAsnsmain.Zasnno);//ASN号
                            parameters.Add("@orderType", 20);//类型 ASN
                            parameters.Add("@orderStatus", 20);//状态 已生成

                            SysVendor sysVendor = sysVendorAll.Where(a => a.VendorCode == sapAsnsmain.Lifnr).FirstOrDefault();//供应商信息
                            parameters.Add("@vendorId", sysVendor == null ? 0 : sysVendor.VendorId);//供应商ID
                            parameters.Add("@vendorCode", sapAsnsmain.Lifnr);//供应商代码
                            parameters.Add("@seDate", sapAsnsmain.Zdate);//计划交货日期
                            parameters.Add("@seTime", sapAsnsmain.Zcjsj);//计划交货时间

                            SysFactory sysFactory = sysFactoryAll.Where(a => a.FactoryCode == sapAsnsmain.Werks).FirstOrDefault();//工厂
                            parameters.Add("@factoryId", sysFactory == null ? 0 : sysFactory.FactoryId);//工厂ID
                            parameters.Add("@factoryCode", sapAsnsmain.Werks);//工厂代码

                            parameters.Add("@PSTYP", sapAsnsmain.Pstyp);//采购标识0：标准，3：外协加工，2：寄售，1：限制，7：库存转存
                            parameters.Add("@enabled", 'Y');//启用
                            parameters.Add("@createUserid", 0);//创建人
                            parameters.Add("@createTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));//创建日期
                            parameters.Add("@guid", guidStr);//guid

                            parametersList.Add(parameters);
                        }
                    }

                    #endregion

                    SqlStringBuilder = new StringBuilder(1024);
                    SqlStringBuilder.Append("update SAP_ASN set SYNFLG='Y',SYNTIM=@SYNTIM  where Zasnno=@Zasnno and SID=@SID ");//更新同步状态
                    sqlList.Add(SqlStringBuilder.ToString());

                    parameters = new DynamicParameters();
                    parameters.Add("@Zasnno", sapAsns[s].Zasnno);//Zasnno
                    parameters.Add("@SID", sapAsns[s].Sid);//Sid
                    parameters.Add("@SYNTIM", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));//同步时间
                    parametersList.Add(parameters);

                    bool staResult = ExecuteTransaction(sqlList, parametersList);
                    if (staResult == false)
                    {
                        sqlList = new List<string>();
                        parametersList = new List<DynamicParameters>();
                        SqlStringBuilder = new StringBuilder(1024);
                        SqlStringBuilder.Append("update SAP_ASN set SYNFLG='E',ERRMSG=@ERRMSG,SYNTIM=@SYNTIM  where ZASNNO=@Zasnno and SID=@SID ");//更新同步状态
                        sqlList.Add(SqlStringBuilder.ToString());

                        parameters = new DynamicParameters();
                        parameters.Add("@Zasnno", sapAsns[s].Zasnno);//Zasnno
                        parameters.Add("@SID", sapAsns[s].Sid);//Sid
                        parameters.Add("@ERRMSG", "同步错误，请检查接口数据！");//错误
                        parameters.Add("@SYNTIM", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));//同步时间
                        parametersList.Add(parameters);
                        ExecuteTransaction(sqlList, parametersList);
                        return false;
                    }
                }
                return true;
            }
        }


        /// <summary>
        /// 获取SAP系统把PO传递到WMS用于采购收货
        /// </summary>
        /// <returns></returns>
        public List<SapDspo> GetDSPODataInfo()
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                StringBuilder sql = new StringBuilder(1024);
                sql.Append("SELECT TOP 1000 EBELN, COUNT(1),ZDATE,SID FROM sap_dspo (nolock) ");
                sql.Append("WHERE SYNFLG = 'N' ");
                sql.Append("GROUP BY ZDATE,EBELN,SID ");
                sql.Append("ORDER BY ZDATE ");

                return dbConn.Query<SapDspo>(sql.ToString()).ToList();
            }
        }

        /// <summary>
        /// 添加SAP系统把PO传递到WMS用于采购收货
        /// </summary>
        /// <param name="sapCu"></param>
        /// <returns></returns>
        public bool InsertPODataInfo(List<SapDspo> sapDspos)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                dbConn.Open();
                StringBuilder SqlStringBuilder = new StringBuilder(1024);
                DynamicParameters parameters = new DynamicParameters();

                StringBuilder factoryStringBuilder = new StringBuilder(1024);
                factoryStringBuilder.Append("select * from sys_factory (nolock) where enabled='Y'");//工厂
                List<SysFactory> sysFactoryAll = dbConn.Query<SysFactory>(factoryStringBuilder.ToString()).ToList();

                StringBuilder vendorStringBuilder = new StringBuilder(1024);
                vendorStringBuilder.Append("select * from sys_vendor (nolock) where enabled='Y'");//供应商信息
                List<SysVendor> sysVendorAll = dbConn.Query<SysVendor>(vendorStringBuilder.ToString()).ToList();

                StringBuilder partNoStringBuilder = new StringBuilder(1024);
                partNoStringBuilder.Append("select * from sys_part (nolock) where enabled='Y' ");//零件号
                List<SysPart> sysPartAll = dbConn.Query<SysPart>(partNoStringBuilder.ToString()).ToList();

                for (int s = 0; s < sapDspos.Count; s++)
                {
                    List<string> sqlList = new List<string>();
                    List<DynamicParameters> parametersList = new List<DynamicParameters>();

                    #region 明细
                    SqlStringBuilder = new StringBuilder(1024);
                    SqlStringBuilder.Append("SELECT * FROM wms_purchase_detail (nolock) ");
                    SqlStringBuilder.Append("WHERE order_no = '" + sapDspos[s].Ebeln + "'");
                    List<WmsPurchaseDetail> wmsPurchaseDetailsList = dbConn.Query<WmsPurchaseDetail>(SqlStringBuilder.ToString()).ToList();

                    SqlStringBuilder = new StringBuilder(1024);
                    SqlStringBuilder.Append("SELECT EBELN,LIFNR,EVRTP,MATNR,SUM(ZDEV_NUM) SumZdevNum,COUNT(1) BoxQty,UNIT,PSTYP,ZDATE,ZCJSJ,WERKS,LGORT,ITEMTYPE,PURCHASENO FROM sap_dspo (nolock) WHERE EBELN='" + sapDspos[s].Ebeln + "' AND SID ='" + sapDspos[s].Sid + "' AND Zstas='X' ");
                    SqlStringBuilder.Append("	GROUP BY EBELN,LIFNR,EVRTP,MATNR,UNIT,PSTYP,ZDATE,ZCJSJ,WERKS,LGORT,ITEMTYPE,PURCHASENO  ");
                    List<SapDspo_Extend> sapDsposDetailsDel = dbConn.Query<SapDspo_Extend>(SqlStringBuilder.ToString()).ToList();
                    //单据明细
                    foreach (SapDspo_Extend sapDsposDetail in sapDsposDetailsDel)
                    {
                        WmsPurchaseDetail wmsPurchaseDetailInfo = wmsPurchaseDetailsList.Where(a => a.OrderNo == sapDsposDetail.Ebeln && a.PartNo == sapDsposDetail.Matnr && a.ItemNo==sapDsposDetail.Evrtp.ToString()).FirstOrDefault();
                        if (wmsPurchaseDetailInfo != null)
                        {
                            SqlStringBuilder = new StringBuilder(1024);
                            SqlStringBuilder.Append("UPDATE dbo.wms_purchase_detail ");
                            SqlStringBuilder.Append("   SET part_no = @partNo,item_status=@itemStatus,qty = @qty,box_qty=@boxQty ");
                            SqlStringBuilder.Append("      ,update_userid = @updateUserid,update_time = @updateTime ");
                            SqlStringBuilder.Append(" WHERE order_no = @orderNo and part_no=@partNo and item_no=@itemNo");

                            sqlList.Add(SqlStringBuilder.ToString());

                            parameters = new DynamicParameters();
                            parameters.Add("@orderNo", sapDsposDetail.Ebeln);//PO号
                            parameters.Add("@itemNo", sapDsposDetail.Evrtp);//行号
                            parameters.Add("@partNo", sapDsposDetail.Matnr);//物料编码
                            parameters.Add("@qty", 0);//数量
                            parameters.Add("@boxQty", 0);//包装数量
                            parameters.Add("@itemStatus", (int)WmsEnumUtil.PurchaseOrderDetailStatus.COMPLETED);//状态 已完成
                            parameters.Add("@updateUserid", 0);//创建人
                            parameters.Add("@updateTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));//创建日期
                            parametersList.Add(parameters);
                        }
                    }

                    SqlStringBuilder = new StringBuilder(1024);
                    SqlStringBuilder.Append("SELECT EBELN,LIFNR,EVRTP,MATNR,SUM(ZDEV_NUM) SumZdevNum,COUNT(1) BoxQty,UNIT,PSTYP,ZDATE,ZCJSJ,WERKS,LGORT,ITEMTYPE,PURCHASENO FROM sap_dspo (nolock) WHERE EBELN='" + sapDspos[s].Ebeln + "' AND SID ='" + sapDspos[s].Sid + "' AND Zstas!='X' ");
                    SqlStringBuilder.Append("	GROUP BY EBELN,LIFNR,EVRTP,MATNR,UNIT,PSTYP,ZDATE,ZCJSJ,WERKS,LGORT,ITEMTYPE,PURCHASENO  ");
                    List<SapDspo_Extend> sapDsposDetails = dbConn.Query<SapDspo_Extend>(SqlStringBuilder.ToString()).ToList();
                    //单据明细
                    foreach (SapDspo sapDsposDetail in sapDsposDetails)
                    {
                        WmsPurchaseDetail wmsPurchaseDetailInfo = wmsPurchaseDetailsList.Where(a => a.OrderNo == sapDsposDetail.Ebeln && a.PartNo == sapDsposDetail.Matnr && a.ItemNo == sapDsposDetail.Evrtp.ToString()).FirstOrDefault();
                        if (wmsPurchaseDetailInfo != null)
                        {
                            SqlStringBuilder = new StringBuilder(1024);
                            SqlStringBuilder.Append("UPDATE dbo.wms_purchase_detail ");
                            SqlStringBuilder.Append("   SET item_no = @itemNo,part_id = @partId ");
                            SqlStringBuilder.Append("      ,part_no = @partNo,part_spec = @partSpec ");
                            SqlStringBuilder.Append("      ,qty = @qty,box_qty=@boxQty,snp_qty=@snpQty,unit = @unit ");
                            SqlStringBuilder.Append("      ,erp_warehouse = @erpWarehouse,item_status = @itemStatus ");
                            SqlStringBuilder.Append("      ,factory_id = @factoryId,factory_code = @factoryCode ");
                            SqlStringBuilder.Append("      ,enabled = @enabled,update_userid = @updateUserid ");
                            SqlStringBuilder.Append("      ,update_time = @updateTime ");
                            SqlStringBuilder.Append(" WHERE order_no = @orderNo and part_no=@partNo and item_no=@itemNo");

                            sqlList.Add(SqlStringBuilder.ToString());

                            parameters = new DynamicParameters();
                            parameters.Add("@orderNo", sapDsposDetail.Ebeln);//PO号
                            parameters.Add("@itemNo", sapDsposDetail.Evrtp);//PO item

                            List<SysPart> sysPart = sysPartAll.Where(a => a.PartNo == sapDsposDetail.Matnr).ToList();//零件号ID
                            if (sysPart.Count == 0)
                            {
                                parameters.Add("@partId", 0);//物料Id
                                parameters.Add("@partSpec", "");//物料描述
                                parameters.Add("@snpQty", 0);//标准包装
                            }
                            else
                            {
                                parameters.Add("@partId", sysPart[0].PartId);//物料Id
                                parameters.Add("@partSpec", sysPart[0].PartSpec);//物料描述
                                parameters.Add("@snpQty", sysPart[0].DefaultBoxQty);//标准包装
                            }
                            parameters.Add("@partNo", sapDsposDetail.Matnr);//物料编码

                            parameters.Add("@boxQty", sapDsposDetail.BoxQty);//包装数量
                            parameters.Add("@qty", sapDsposDetail.SumZdevNum);//数量

                            parameters.Add("@unit", sapDsposDetail.Unit);//单位
                            parameters.Add("@erpWarehouse", sapDsposDetail.Lgort);//库存地
                            parameters.Add("@itemStatus", (int)WmsEnumUtil.PurchaseOrderDetailStatus.GENERATED);//状态 已生成

                            SysFactory sysFactory = sysFactoryAll.Where(a => a.FactoryCode == sapDsposDetail.Werks).FirstOrDefault();//工厂
                            parameters.Add("@factoryId", sysFactory == null ? 0 : sysFactory.FactoryId);//工厂ID

                            parameters.Add("@factoryCode", sapDsposDetail.Werks);//工厂代码
                            parameters.Add("@enabled", 'Y');//启用
                            parameters.Add("@updateUserid", 0);//创建人
                            parameters.Add("@updateTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));//创建日期
                            parametersList.Add(parameters);
                        }
                        else
                        {
                            SqlStringBuilder = new StringBuilder(1024);
                            SqlStringBuilder.Append("INSERT INTO dbo.wms_purchase_detail(order_no,item_no,part_id,part_no,part_spec,qty,rec_qty,box_qty,rec_box_qty,snp_qty");
                            SqlStringBuilder.Append("           ,unit,erp_warehouse,item_status,factory_id,factory_code ");
                            SqlStringBuilder.Append("           ,enabled,create_userid,create_time) ");
                            SqlStringBuilder.Append("     VALUES(@orderNo,@itemNo,@partId,@partNo,@partSpec,@qty,0,@boxQty,0,@snpQty ");
                            SqlStringBuilder.Append("           ,@unit,@erpWarehouse,@itemStatus,@factoryId,@factoryCode,@enabled ");
                            SqlStringBuilder.Append("           ,@createUserid,@createTime) ");

                            sqlList.Add(SqlStringBuilder.ToString());

                            parameters = new DynamicParameters();
                            parameters.Add("@orderNo", sapDsposDetail.Ebeln);//PO号
                            parameters.Add("@itemNo", sapDsposDetail.Evrtp);//PO item

                            SysPart sysPart = sysPartAll.Where(a => a.PartNo == sapDsposDetail.Matnr).FirstOrDefault();//零件号ID
                            if (sysPart == null)
                            {
                                parameters.Add("@partId", 0);//物料Id
                                parameters.Add("@partSpec", "");//物料描述
                                parameters.Add("@snpQty", 0);//标准包装
                            }
                            else
                            {
                                parameters.Add("@partId", sysPart.PartId);//物料Id
                                parameters.Add("@partSpec", sysPart.PartSpec);//物料描述
                                parameters.Add("@snpQty", sysPart.DefaultBoxQty);//标准包装
                            }
                            parameters.Add("@partNo", sapDsposDetail.Matnr);//物料编码

                            parameters.Add("@boxQty", sapDsposDetail.BoxQty);//包装数量
                            parameters.Add("@qty", sapDsposDetail.SumZdevNum);//数量

                            parameters.Add("@unit", sapDsposDetail.Unit);//单位
                            parameters.Add("@erpWarehouse", sapDsposDetail.Lgort);//库存地
                            parameters.Add("@itemStatus", (int)WmsEnumUtil.PurchaseOrderDetailStatus.GENERATED);//状态 已生成

                            SysFactory sysFactory = sysFactoryAll.Where(a => a.FactoryCode == sapDsposDetail.Werks).FirstOrDefault();//工厂
                            parameters.Add("@factoryId", sysFactory == null ? 0 : sysFactory.FactoryId);//工厂ID
                            parameters.Add("@factoryCode", sapDsposDetail.Werks);//工厂代码
                            parameters.Add("@enabled", 'Y');//启用
                            parameters.Add("@createUserid", 0);//创建人
                            parameters.Add("@createTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));//创建日期
                            parametersList.Add(parameters);
                        }
                    }
                    #endregion

                    #region 主表

                    SqlStringBuilder = new StringBuilder(1024);
                    SqlStringBuilder.Append("SELECT * FROM wms_purchase (nolock) ");
                    SqlStringBuilder.Append("WHERE order_no = '" + sapDspos[s].Ebeln + "'");
                    List<WmsPurchase> wmsPurchasesList = dbConn.Query<WmsPurchase>(SqlStringBuilder.ToString()).ToList();
                    string guidStr = Guid.NewGuid().ToString();

                    SqlStringBuilder = new StringBuilder(1024);
                    SqlStringBuilder.Append("SELECT EBELN,LIFNR,EVRTP,MATNR,ZDEV_NUM,UNIT,PSTYP,ZDATE,ZCJSJ,WERKS,LGORT,ITEMTYPE,PURCHASENO FROM sap_dspo (nolock) WHERE EBELN='" + sapDspos[s].Ebeln + "' AND SID ='" + sapDspos[s].Sid + "' AND ZSTAS='X' ");
                    SapDspoInterface_Extend sapDsposmainDel = dbConn.Query<SapDspoInterface_Extend>(SqlStringBuilder.ToString()).FirstOrDefault();

                    if (wmsPurchasesList.Count > 0)
                    {
                        if (sapDsposmainDel != null)
                        {
                            SqlStringBuilder = new StringBuilder(1024);
                            SqlStringBuilder.Append("UPDATE dbo.wms_purchase ");
                            SqlStringBuilder.Append("   SET order_status = @orderStatus ");
                            SqlStringBuilder.Append("      ,update_userid = @updateUserid,update_time = @updateTime ");
                            SqlStringBuilder.Append(" WHERE order_no = @orderNo ");
                            sqlList.Add(SqlStringBuilder.ToString());

                            parameters = new DynamicParameters();
                            parameters.Add("@orderNo", sapDsposmainDel.Ebeln);//ASN号
                            parameters.Add("@orderStatus", 60);//状态 已关闭
                            parameters.Add("@updateUserid", 0);//更新人
                            parameters.Add("@updateTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));//更新日期
                            parametersList.Add(parameters);
                        }
                    }

                    SqlStringBuilder = new StringBuilder(1024);
                    SqlStringBuilder.Append("SELECT EBELN,LIFNR,EVRTP,MATNR,ZDEV_NUM,UNIT,PSTYP,ZDATE,ZCJSJ,WERKS,LGORT,ITEMTYPE,PURCHASENO FROM sap_dspo (nolock) WHERE EBELN='" + sapDspos[s].Ebeln + "' AND SID ='" + sapDspos[s].Sid + "' AND ZSTAS!='X' ");
                    SapDspoInterface_Extend sapDsposmain = dbConn.Query<SapDspoInterface_Extend>(SqlStringBuilder.ToString()).FirstOrDefault();

                    if (sapDsposmain != null)
                    {
                        if (wmsPurchasesList.Count > 0)
                        {
                            SqlStringBuilder = new StringBuilder(1024);
                            SqlStringBuilder.Append("UPDATE dbo.wms_purchase ");
                            SqlStringBuilder.Append("   SET order_type = @orderType,order_status = @orderStatus ");
                            SqlStringBuilder.Append("      ,vendor_id = @vendorId,vendor_code = @vendorCode,se_date = @seDate ");
                            SqlStringBuilder.Append("      ,se_time = @seTime,factory_id = @factoryId,factory_code = @factoryCode ");
                            SqlStringBuilder.Append("      ,enabled = @enabled,update_userid = @updateUserid,update_time = @updateTime ");
                            SqlStringBuilder.Append(" WHERE order_no = @orderNo ");
                            sqlList.Add(SqlStringBuilder.ToString());

                            parameters = new DynamicParameters();
                            parameters.Add("@orderNo", sapDsposmain.Ebeln);//PO号
                            parameters.Add("@orderType", sapDsposmain.ItemType);//类型 PO
                            parameters.Add("@orderStatus", 10);//状态 创建
                            SysVendor sysVendor = sysVendorAll.Where(a => a.VendorCode == sapDsposmain.Lifnr).FirstOrDefault();//供应商信息
                            parameters.Add("@vendorId", sysVendor == null ? 0 : sysVendor.VendorId);//供应商ID

                            parameters.Add("@vendorCode", sapDsposmain.Lifnr);//供应商代码
                            parameters.Add("@seDate", sapDsposmain.Zdate);//计划交货日期
                            parameters.Add("@seTime", sapDsposmain.Zcjsj);//计划交货时间

                            SysFactory sysFactory = sysFactoryAll.Where(a => a.FactoryCode == sapDsposmain.Werks).FirstOrDefault();//工厂
                            parameters.Add("@factoryId", sysFactory == null ? 0 : sysFactory.FactoryId);//工厂ID
                            parameters.Add("@factoryCode", sapDsposmain.Werks);//工厂代码

                            parameters.Add("@enabled", 'Y');//启用
                            parameters.Add("@updateUserid", 0);//更新人
                            parameters.Add("@updateTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));//更新日期

                            parametersList.Add(parameters);
                        }
                        else
                        {
                            SqlStringBuilder = new StringBuilder(1024);
                            SqlStringBuilder.Append("INSERT INTO dbo.wms_purchase(order_no,order_type,order_status,vendor_id,vendor_code ");
                            SqlStringBuilder.Append("           ,se_date,se_time,factory_id,factory_code,ref_order_no,enabled,create_userid,create_time,guid) ");
                            SqlStringBuilder.Append("     VALUES(@orderNo,@orderType,@orderStatus,@vendorId,@vendorCode,@seDate,@seTime ");
                            SqlStringBuilder.Append("           ,@factoryId,@factoryCode,@ref_order_no,@enabled,@createUserid,@createTime,@guid) ");

                            sqlList.Add(SqlStringBuilder.ToString());

                            parameters = new DynamicParameters();
                            parameters.Add("@orderNo", sapDsposmain.Ebeln);//PO号
                            parameters.Add("@orderType", sapDsposmain.ItemType);//类型 PO
                            parameters.Add("@orderType", sapDsposmain.ItemType);//类型 PO
                            parameters.Add("@orderStatus", 10);//状态 创建

                            SysVendor sysVendor = sysVendorAll.Where(a => a.VendorCode == sapDsposmain.Lifnr).FirstOrDefault();//供应商信息
                            parameters.Add("@vendorId", sysVendor == null ? 0 : sysVendor.VendorId);//供应商ID
                            parameters.Add("@vendorCode", sapDsposmain.Lifnr);//供应商代码
                            parameters.Add("@seDate", sapDsposmain.Zdate);//计划交货日期
                            parameters.Add("@seTime", sapDsposmain.Zcjsj);//计划交货时间

                            SysFactory sysFactory = sysFactoryAll.Where(a => a.FactoryCode == sapDsposmain.Werks).FirstOrDefault();//工厂
                            parameters.Add("@factoryId", sysFactory == null ? 0 : sysFactory.FactoryId);//工厂ID
                            parameters.Add("@factoryCode", sapDsposmain.Werks);//工厂代码
                            parameters.Add("@ref_order_no", sapDsposmain.Purchaseno);//关联订单号

                            parameters.Add("@enabled", 'Y');//启用
                            parameters.Add("@createUserid", 0);//创建人
                            parameters.Add("@createTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));//创建日期
                            parameters.Add("@guid", guidStr);//guid

                            parametersList.Add(parameters);
                        }
                    }

                    #endregion

                    SqlStringBuilder = new StringBuilder(1024);
                    SqlStringBuilder.Append("update sap_dspo set SYNFLG='Y',SYNTIM=@SYNTIM  where Ebeln=@Ebeln and SID=@SID ");//更新同步状态
                    sqlList.Add(SqlStringBuilder.ToString());

                    parameters = new DynamicParameters();
                    parameters.Add("@Ebeln", sapDspos[s].Ebeln);//Ebeln
                    parameters.Add("@SID", sapDspos[s].Sid);//Sid
                    parameters.Add("@SYNTIM", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));//同步时间
                    parametersList.Add(parameters);

                    bool staResult = ExecuteTransaction(sqlList, parametersList);
                    if (staResult == false)
                    {
                        sqlList = new List<string>();
                        parametersList = new List<DynamicParameters>();
                        SqlStringBuilder = new StringBuilder(1024);
                        SqlStringBuilder.Append("update sap_dspo set SYNFLG='E',ERRMSG=@ERRMSG,SYNTIM=@SYNTIM  where EBELN=@Ebeln and SID=@SID ");//更新同步状态
                        sqlList.Add(SqlStringBuilder.ToString());

                        parameters = new DynamicParameters();
                        parameters.Add("@Ebeln", sapDspos[s].Ebeln);//Ebeln
                        parameters.Add("@SID", sapDspos[s].Sid);//Sid
                        parameters.Add("@ERRMSG", "同步错误，请检查接口数据！");//错误
                        parameters.Add("@SYNTIM", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));//同步时间
                        parametersList.Add(parameters);
                        ExecuteTransaction(sqlList, parametersList);
                        return false;
                    }
                }
                return true;
            }
        }
        #endregion

        #region 移动
        /// <summary>
        /// 获取SAP系统将一定期间内待发运交货单信息发布到WMS用于后续捡配发货
        /// </summary>
        /// <returns></returns>
        public List<SapDn> GetSalesAndDeliveryPlanInfo()
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                StringBuilder sql = new StringBuilder(1024);
                sql.Append("SELECT top 1000 VBELN,COUNT(1),LFDAT,SID FROM sap_dn (nolock) ");
                sql.Append("WHERE  SYNFLG = 'N' ");
                sql.Append("GROUP BY LFDAT,VBELN,SID ");
                sql.Append("ORDER BY LFDAT ");

                return dbConn.Query<SapDn>(sql.ToString()).ToList();
            }
        }

        /// <summary>
        /// 添加SAP系统将一定期间内待发运交货单信息发布到WMS用于后续捡配发货
        /// </summary>
        /// <param name="sapCu"></param>
        /// <returns></returns>
        public bool InsertSalesAndDeliveryPlanInfo(List<SapDn> sapDns)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                List<string> sqlList;
                List<DynamicParameters> parametersList;
                StringBuilder SqlStringBuilder;
                DynamicParameters parameters;
                try
                {
                    StringBuilder stringBuilder = new StringBuilder();
                    SqlStringBuilder = new StringBuilder(1024);
                    parameters = new DynamicParameters();

                    StringBuilder factoryStringBuilder = new StringBuilder(1024);
                    factoryStringBuilder.Append("select * from sys_factory (nolock) where enabled='Y'");//工厂
                    List<SysFactory> sysFactoryAll = dbConn.Query<SysFactory>(factoryStringBuilder.ToString()).ToList();

                    StringBuilder customerStringBuilder = new StringBuilder(1024);
                    customerStringBuilder.Append("select * from sys_customer (nolock) where enabled='Y'");//客户信息
                    List<SysCustomer> sysCustomerAll = dbConn.Query<SysCustomer>(customerStringBuilder.ToString()).ToList();

                    StringBuilder partNoStringBuilder = new StringBuilder(1024);
                    partNoStringBuilder.Append("select * from sys_part (nolock) where enabled='Y' ");//零件号
                    List<SysPart> sysPartAll = dbConn.Query<SysPart>(partNoStringBuilder.ToString()).ToList();

                    for (int s = 0; s < sapDns.Count; s++)
                    {
                        sqlList = new List<string>();
                        parametersList = new List<DynamicParameters>();
                        string guidStr = Guid.NewGuid().ToString();

                        #region 明细
                        SqlStringBuilder = new StringBuilder(1024);
                        SqlStringBuilder.Append("SELECT * FROM wms_outstock_detail (nolock) ");
                        SqlStringBuilder.Append("WHERE order_no = '" + sapDns[s].Vbeln + "'");
                        List<WmsOutstockDetail> wmsOutstockDetailsList = dbConn.Query<WmsOutstockDetail>(SqlStringBuilder.ToString()).ToList();

                        SqlStringBuilder = new StringBuilder(1024);
                        SqlStringBuilder.Append("SELECT VBELN,POSNR,WERKS,MATNR,LGORT,LFDAT,KUNNR,MATNR,KDMAT,SUM(LFIMG) SumLfimg,MEINS FROM SAP_DN (nolock) WHERE VBELN='" + sapDns[s].Vbeln + "' AND SID ='" + sapDns[s].Sid + "' ");
                        SqlStringBuilder.Append("	GROUP BY VBELN,POSNR,WERKS,MATNR,LGORT,LFDAT,KUNNR,MATNR,KDMAT,MEINS ");
                        List<SapDn> sapDnsDetails = dbConn.Query<SapDn>(SqlStringBuilder.ToString()).ToList();
                        //单据明细
                        foreach (SapDn sapDnDetail in sapDnsDetails)
                        {
                            SysFactory sysFactory = sysFactoryAll.Where(a => a.FactoryCode == sapDnDetail.Werks).FirstOrDefault();//工厂
                            SysCustomer sysCustomers = sysCustomerAll.Where(a => a.CustomerCode == sapDnDetail.Kunnr).FirstOrDefault();//客户信息
                            SysPart sysPart = sysPartAll.Where(a => a.PartNo == sapDnDetail.Matnr).FirstOrDefault();//零件号ID

                            WmsOutstockDetail wmsOutstockDetailInfo = wmsOutstockDetailsList.Where(a => a.OrderNo == sapDnDetail.Vbeln && a.PartNo == sapDnDetail.Matnr).FirstOrDefault();
                            if (wmsOutstockDetailInfo != null)
                            {
                                SqlStringBuilder = new StringBuilder(1024);
                                SqlStringBuilder.Append("UPDATE dbo.wms_outstock_detail ");
                                SqlStringBuilder.Append("   SET item_no = @itemNo,part_id = @partId ");
                                SqlStringBuilder.Append("      ,part_no = @partNo,part_spec = @partSpec ");
                                SqlStringBuilder.Append("      ,qty = @qty,unit = @unit ");
                                SqlStringBuilder.Append("      ,plan_date = @planDate ");
                                SqlStringBuilder.Append("      ,item_status = @itemStatus ");
                                SqlStringBuilder.Append("      ,src_erp_warehouse = @srcErpWarehouse ");
                                SqlStringBuilder.Append("      ,factory_id = @factoryId,factory_code = @factoryCode ");
                                SqlStringBuilder.Append("      ,enabled = @enabled,update_userid = @updateUserid ");
                                SqlStringBuilder.Append("      ,update_time = @updateTime ");
                                SqlStringBuilder.Append(" WHERE order_no = @orderNo and part_no = @partNo  ");

                                sqlList.Add(SqlStringBuilder.ToString());

                                parameters = new DynamicParameters();
                                parameters.Add("@orderNo", sapDnDetail.Vbeln);//销售交货单
                                parameters.Add("@itemNo", sapDnDetail.Posnr);//PO item

                                if (sysPart == null)
                                {
                                    parameters.Add("@partId", 0);//物料Id
                                    parameters.Add("@partSpec", "");//物料描述
                                }
                                else
                                {
                                    parameters.Add("@partId", sysPart.PartId);//物料Id
                                    parameters.Add("@partSpec", sysPart.PartSpec);//物料描述
                                }
                                parameters.Add("@partNo", sapDnDetail.Matnr);//物料编码
                                parameters.Add("@qty", sapDnDetail.SumLfimg);//交货数量
                                parameters.Add("@unit", sapDnDetail.Meins);//单位

                                parameters.Add("@planDate", Convert.ToDateTime(sapDnDetail.Lfdat).ToShortDateString());//计划交货日期
                                parameters.Add("@itemStatus", 10);//状态
                                parameters.Add("@srcErpWarehouse", sapDnDetail.Lgort);//库存地

                                parameters.Add("@factoryId", sysFactory == null ? 0 : sysFactory.FactoryId);//工厂ID
                                parameters.Add("@factoryCode", sapDnDetail.Werks);//工厂代码
                                parameters.Add("@enabled", 'Y');//启用
                                parameters.Add("@updateUserid", 0);//修改人
                                parameters.Add("@updateTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));//修改日期
                                parametersList.Add(parameters);
                            }
                            else
                            {
                                SqlStringBuilder = new StringBuilder(1024);
                                SqlStringBuilder.Append("INSERT INTO dbo.wms_outstock_detail(order_no,item_no,part_id,part_no,part_spec,qty,pick_qty,out_qty,unit ");
                                SqlStringBuilder.Append("           ,plan_date,plan_time,item_status,src_warehouse_id,src_warehouse_name,src_zone_id,src_zone_name ");
                                SqlStringBuilder.Append("           ,src_locate_id,src_locate_name,src_erp_warehouse,factory_id,factory_code,enabled ");
                                SqlStringBuilder.Append("           ,create_userid,create_time) ");
                                SqlStringBuilder.Append("     VALUES(@orderNo,@itemNo,@partId,@partNo,@partSpec,@qty,@pickQty,@outQty,@unit,@planDate ");
                                SqlStringBuilder.Append("           ,'',@itemStatus,0,'',0,'' ");
                                SqlStringBuilder.Append("           ,0,'',@srcErpWarehouse,@factoryId,@factoryCode,@enabled ");
                                SqlStringBuilder.Append("           ,@createUserid,@createTime) ");
                                sqlList.Add(SqlStringBuilder.ToString());

                                parameters = new DynamicParameters();
                                parameters.Add("@orderNo", sapDnDetail.Vbeln);//销售交货单
                                parameters.Add("@itemNo", sapDnDetail.Posnr);//PO item

                                if (sysPart == null)
                                {
                                    parameters.Add("@partId", 0);//物料Id
                                    parameters.Add("@partSpec", "");//物料描述
                                }
                                else
                                {
                                    parameters.Add("@partId", sysPart.PartId);//物料Id
                                    parameters.Add("@partSpec", sysPart.PartSpec);//物料描述
                                }
                                parameters.Add("@partNo", sapDnDetail.Matnr);//物料编码

                                parameters.Add("@qty", sapDnDetail.SumLfimg);//交货数量
                                parameters.Add("@pickQty", 0);//
                                parameters.Add("@outQty", 0);//

                                parameters.Add("@unit", sapDnDetail.Meins);//单位

                                parameters.Add("@planDate",Convert.ToDateTime(sapDnDetail.Lfdat).ToShortDateString());//计划交货日期
                                parameters.Add("@itemStatus", 10);//状态
                                parameters.Add("@srcErpWarehouse", sapDnDetail.Lgort);//库存地

                                parameters.Add("@factoryId", sysFactory == null ? 0 : sysFactory.FactoryId);//工厂ID
                                parameters.Add("@factoryCode", sapDnDetail.Werks);//工厂代码
                                parameters.Add("@enabled", 'Y');//启用
                                parameters.Add("@createUserid", 0);//创建人
                                parameters.Add("@createTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));//创建日期
                                parametersList.Add(parameters);
                            }
                        }
                        #endregion

                        SqlStringBuilder = new StringBuilder(1024);
                        SqlStringBuilder.Append("SELECT VBELN,POSNR,WERKS,MATNR,LGORT,LFDAT,KUNNR,MATNR,KDMAT,LFIMG,MEINS,DELIVERTNOTICE,WLCOMPANY,ENABLED FROM SAP_DN (nolock) WHERE VBELN='" + sapDns[s].Vbeln + "' AND SID ='" + sapDns[s].Sid + "'");
                        SapDnInterface_Extend sapDnsmain = dbConn.Query<SapDnInterface_Extend>(SqlStringBuilder.ToString()).FirstOrDefault();
                        if (sapDnsmain != null)
                        {
                            //主表
                            guidStr = Guid.NewGuid().ToString();
                            stringBuilder = new StringBuilder();
                            stringBuilder.Append(" SELECT * from wms_outstock (nolock) WHERE order_no='" + sapDnsmain.Vbeln + "' ");
                            List<WmsOutstock> wmsOutstocks = dbConn.Query<WmsOutstock>(stringBuilder.ToString()).ToList();
                            if (wmsOutstocks.Count > 0)
                            {
                                SqlStringBuilder = new StringBuilder(1024);
                                SqlStringBuilder.Append("UPDATE dbo.wms_outstock ");
                                SqlStringBuilder.Append("   SET order_no = @orderNo,order_type = @orderType,order_status = @orderStatus ");
                                SqlStringBuilder.Append("      ,factory_id = @factoryId,factory_code = @factoryCode,ref_order_no=@ref_order_no,LogisticsCompany=@LogisticsCompany ");
                                SqlStringBuilder.Append("      ,enabled = @enabled,update_userid = @updateUserid,update_time = @updateTime ");
                                SqlStringBuilder.Append(" WHERE order_no = @orderNo ");
                                sqlList.Add(SqlStringBuilder.ToString());

                                parameters = new DynamicParameters();
                                parameters.Add("@orderNo", sapDnsmain.Vbeln);//
                                parameters.Add("@orderType", (int)WmsEnumUtil.OutStockType.SALE_SHIPPING_NJIS);//类型
                                parameters.Add("@orderStatus", (int)WmsEnumUtil.MoveOrderStatus.CREATE);//状态

                                SysFactory sysFactory = sysFactoryAll.Where(a => a.FactoryCode == sapDnsmain.Werks).FirstOrDefault();//工厂
                                SysCustomer sysCustomers = sysCustomerAll.Where(a => a.CustomerCode == sapDnsmain.Kunnr).FirstOrDefault();//客户信息
                                parameters.Add("@factoryId", sysFactory == null ? 0 : sysFactory.FactoryId);//工厂ID
                                parameters.Add("@factoryCode", sapDnsmain.Werks);//工厂代码

                                parameters.Add("@enabled", sapDnsmain.enabled);//启用
                                parameters.Add("@updateUserid", 0);//更新人
                                parameters.Add("@updateTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));//更新日期
                                parameters.Add("@ref_order_no", sapDnsmain.Delivertnotice);//关联订单
                                parameters.Add("@LogisticsCompany", sapDnsmain.WLCompany);//物流公司

                                parametersList.Add(parameters);
                            }
                            else
                            {
                                SqlStringBuilder = new StringBuilder(1024);
                                SqlStringBuilder.Append("INSERT INTO dbo.wms_outstock(order_no,order_type,order_status,vendor_id,vendor_code,customer_id ");
                                SqlStringBuilder.Append("           ,customer_code,factory_id,factory_code,enabled,create_userid,create_time,guid,ref_order_no,LogisticsCompany) ");
                                SqlStringBuilder.Append("     VALUES(@orderNo,@orderType,@orderStatus,0,'',@customerId,@customerCode ");
                                SqlStringBuilder.Append("           ,@factoryId,@factoryCode,@enabled,@createUserid,@createTime,@guid,@ref_order_no,@LogisticsCompany) ");
                                sqlList.Add(SqlStringBuilder.ToString());

                                parameters = new DynamicParameters();
                                parameters.Add("@orderNo", sapDnsmain.Vbeln);//销售交货单
                                parameters.Add("@orderType", (int)WmsEnumUtil.OutStockType.SALE_SHIPPING_NJIS);//类型
                                parameters.Add("@orderStatus", (int)WmsEnumUtil.MoveOrderStatus.CREATE);//状态

                                SysFactory sysFactory = sysFactoryAll.Where(a => a.FactoryCode == sapDnsmain.Werks).FirstOrDefault();//工厂
                                SysCustomer sysCustomers = sysCustomerAll.Where(a => a.CustomerCode == sapDnsmain.Kunnr).FirstOrDefault();//客户信息
                                parameters.Add("@customerId", sysCustomers == null ? 0 : sysCustomers.CustomerId);//客户ID
                                parameters.Add("@customerCode", sapDnsmain.Kunnr);//客户代码

                                parameters.Add("@factoryId", sysFactory == null ? 0 : sysFactory.FactoryId);//工厂ID
                                parameters.Add("@factoryCode", sapDnsmain.Werks);//工厂代码

                                parameters.Add("@enabled", sapDnsmain.enabled);//启用
                                parameters.Add("@createUserid", 0);//创建人
                                parameters.Add("@createTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));//创建日期
                                parameters.Add("@guid", guidStr);//guid
                                parameters.Add("@ref_order_no", sapDnsmain.Delivertnotice);//关联订单
                                parameters.Add("@LogisticsCompany", sapDnsmain.WLCompany);//物流公司

                                parametersList.Add(parameters);
                            }
                        }

                        SqlStringBuilder = new StringBuilder(1024);
                        SqlStringBuilder.Append("update SAP_DN set SYNFLG='Y',SYNTIM=@SYNTIM,ERRMSG=''  where VBELN=@VBELN and SID=@SID ");//更新同步状态
                        sqlList.Add(SqlStringBuilder.ToString());

                        parameters = new DynamicParameters();
                        parameters.Add("@VBELN", sapDns[s].Vbeln);//单号
                        parameters.Add("@SID", sapDns[s].Sid);//ID
                        parameters.Add("@SYNTIM", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));//同步时间
                        parametersList.Add(parameters);

                        bool staResult = ExecuteTransaction(sqlList, parametersList);
                        if (staResult == false)
                        {
                            sqlList = new List<string>();
                            parametersList = new List<DynamicParameters>();
                            SqlStringBuilder = new StringBuilder(1024);
                            SqlStringBuilder.Append("update SAP_DN set SYNFLG='E',ERRMSG=@ERRMSG,SYNTIM=@SYNTIM  where VBELN=@VBELN and SID=@SID ");//更新同步状态
                            sqlList.Add(SqlStringBuilder.ToString());

                            parameters = new DynamicParameters();
                            parameters.Add("@VBELN", sapDns[s].Vbeln);//单号
                            parameters.Add("@SID", sapDns[s].Sid);//I
                            parameters.Add("@ERRMSG", "同步错误，请检查接口数据！");//错误
                            parameters.Add("@SYNTIM", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));//同步时间
                            parametersList.Add(parameters);
                            ExecuteTransaction(sqlList, parametersList);
                            return false;
                        }
                    }
                    return true;
                }
                catch (Exception ex)
                {
                    sqlList = new List<string>();
                    parametersList = new List<DynamicParameters>();
                    SqlStringBuilder = new StringBuilder(1024);
                    SqlStringBuilder.Append("update SAP_DN set SYNFLG='E',ERRMSG=@ERRMSG,SYNTIM=@SYNTIM  where VBELN=@VBELN and SID=@SID ");//更新同步状态
                    sqlList.Add(SqlStringBuilder.ToString());

                    parameters = new DynamicParameters();
                    parameters.Add("@VBELN", sapDns[0].Vbeln);//单号
                    parameters.Add("@SID", sapDns[0].Sid);//I
                    parameters.Add("@ERRMSG", ex.Message);//错误
                    parameters.Add("@SYNTIM", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));//同步时间
                    parametersList.Add(parameters);
                    ExecuteTransaction(sqlList, parametersList);
                    return false;
                }
            }
        }

        /// <summary>
        /// 获取SAP把物料的零星出(入）指令传到WMS
        /// </summary>
        /// <returns></returns>
        public List<SapMisco> GetSporadicEntryAndExitInfo()
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {

                StringBuilder sql = new StringBuilder(1024);
                sql.Append("SELECT top 1000 ZINSTNO,COUNT(1),SID,ZACTION FROM SAP_MISCO (nolock) ");
                sql.Append("WHERE  SYNFLG = 'N' ");
                sql.Append("GROUP BY ZINSTNO,SID,ZACTION ");

                return dbConn.Query<SapMisco>(sql.ToString()).ToList();
            }
        }

        /// <summary>
        /// 添加SAP把物料的零星出(入）指令传到WMS
        /// </summary>
        /// <param name="sapCu"></param>
        /// <returns></returns>
        public bool InsertSporadicEntryAndExitInfo(List<SapMisco> sapMiscos)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {

                StringBuilder stringBuilder = new StringBuilder();
                StringBuilder SqlStringBuilder = new StringBuilder(1024);
                DynamicParameters parameters = new DynamicParameters();

                StringBuilder factoryStringBuilder = new StringBuilder(1024);
                factoryStringBuilder.Append("select * from sys_factory (nolock) where enabled='Y'");//工厂
                List<SysFactory> sysFactoryAll = dbConn.Query<SysFactory>(factoryStringBuilder.ToString()).ToList();

                StringBuilder partNoStringBuilder = new StringBuilder(1024);
                partNoStringBuilder.Append("select * from sys_part (nolock) where enabled='Y' ");//零件号
                List<SysPart> sysPartAll = dbConn.Query<SysPart>(partNoStringBuilder.ToString()).ToList();

                for (int s = 0; s < sapMiscos.Count; s++)
                {
                    List<string> sqlList = new List<string>();
                    List<DynamicParameters> parametersList = new List<DynamicParameters>();
                    SapMisco sapMisco = sapMiscos[s];
                    //C00 零星出库
                    //C01 零星入库
                    //C02  311预留出库
                    //C03  311预留入库
                    //C04  201预留出库
                    if (sapMisco.Zaction.Trim() == "C01" || sapMisco.Zaction.Trim() == "C03")//入库
                    {
                        #region 明细
                        SqlStringBuilder = new StringBuilder(1024);
                        SqlStringBuilder.Append("SELECT * FROM wms_instock_detail (nolock) ");
                        SqlStringBuilder.Append("WHERE order_no = '" + sapMisco.Zinstno + "'");
                        List<WmsInstockDetail> WmsInstockDetailsList = dbConn.Query<WmsInstockDetail>(SqlStringBuilder.ToString()).ToList();

                        SqlStringBuilder = new StringBuilder(1024);
                        SqlStringBuilder.Append("SELECT ZINSTNO,ZEILE,WERKS,LGORT,LGORT,MATNR,SUM(ERFMG) SumErfmg ,ERFME,SOBKZ,HTEXT,ZZLZT,ZACTION,DEPARTMENT,REFORDERNO FROM SAP_MISCO (nolock) WHERE ZINSTNO='" + sapMisco.Zinstno + "' AND SID ='" + sapMisco.Sid + "' AND ZZLZT='X' ");
                        SqlStringBuilder.Append("	GROUP BY ZINSTNO,ZEILE,WERKS,LGORT,LGORT,MATNR,ERFME,SOBKZ,HTEXT,ZZLZT,ZACTION,DEPARTMENT,REFORDERNO ");
                        List<SapMisco_Extend> sapMiscosDetailsDel = dbConn.Query<SapMisco_Extend>(SqlStringBuilder.ToString()).ToList();
                        //单据明细
                        foreach (SapMisco_Extend sapMiscosDel in sapMiscosDetailsDel)
                        {
                            WmsInstockDetail WmsInstockDetailInfo = WmsInstockDetailsList.Where(a => a.OrderNo == sapMiscosDel.Zinstno && a.PartNo == sapMiscosDel.Matnr).FirstOrDefault();
                            if (WmsInstockDetailInfo != null)
                            {
                                SqlStringBuilder = new StringBuilder(1024);
                                SqlStringBuilder.Append("UPDATE dbo.wms_instock_detail ");
                                SqlStringBuilder.Append("   SET item_status=@itemStatus,qty = @qty ");
                                SqlStringBuilder.Append("      ,update_userid = @updateUserid,update_time = @updateTime ");
                                SqlStringBuilder.Append(" WHERE order_no = @orderNo and part_no=@partNo ");

                                sqlList.Add(SqlStringBuilder.ToString());

                                parameters = new DynamicParameters();
                                parameters.Add("@orderNo", sapMiscosDel.Zinstno);//单号
                                parameters.Add("@partNo", sapMiscosDel.Matnr);//物料编码
                                parameters.Add("@qty", 0);//物料编码
                                parameters.Add("@boxQty", 0);//物料编码
                                parameters.Add("@itemStatus", (int)WmsEnumUtil.PurchaseOrderDetailStatus.COMPLETED);//状态 已完成
                                parameters.Add("@updateUserid", 0);//创建人
                                parameters.Add("@updateTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));//创建日期
                                parametersList.Add(parameters);
                            }
                        }

                        SqlStringBuilder = new StringBuilder(1024);
                        SqlStringBuilder.Append("SELECT ZINSTNO,ZEILE,WERKS,LGORT,LGORT,MATNR,SUM(ERFMG) SumErfmg ,ERFME,SOBKZ,HTEXT,ZZLZT,ZACTION,DEPARTMENT,REFORDERNO FROM SAP_MISCO (nolock) WHERE ZINSTNO='" + sapMisco.Zinstno + "' AND SID ='" + sapMisco.Sid + "' AND ZZLZT!='X' ");
                        SqlStringBuilder.Append("	GROUP BY ZINSTNO,ZEILE,WERKS,LGORT,LGORT,MATNR,ERFME,SOBKZ,HTEXT,ZZLZT,ZACTION,DEPARTMENT,REFORDERNO ");
                        List<SapMisco_Extend> sapMiscosDetails = dbConn.Query<SapMisco_Extend>(SqlStringBuilder.ToString()).ToList();
                        //单据明细
                        foreach (SapMisco_Extend sapMiscosDetail in sapMiscosDetails)
                        {
                            SysFactory sysFactory = sysFactoryAll.Where(a => a.FactoryCode == sapMiscosDetail.Werks).FirstOrDefault();//工厂
                            SysPart sysPart = sysPartAll.Where(a => a.PartNo == sapMiscosDetail.Matnr).FirstOrDefault();//零件号ID

                            WmsInstockDetail WmsInstockDetailInfo = WmsInstockDetailsList.Where(a => a.OrderNo == sapMiscosDetail.Zinstno && a.PartNo == sapMiscosDetail.Matnr).FirstOrDefault();
                            if (WmsInstockDetailInfo != null)
                            {
                                SqlStringBuilder = new StringBuilder(1024);
                                SqlStringBuilder.Append("UPDATE dbo.wms_instock_detail ");
                                SqlStringBuilder.Append("   SET item_no = @itemNo,part_id = @partId ");
                                SqlStringBuilder.Append("      ,part_no = @partNo,part_spec = @partSpec ");
                                SqlStringBuilder.Append("      ,qty = @qty,unit = @unit ");
                                SqlStringBuilder.Append("      ,plan_date = @planDate ");
                                SqlStringBuilder.Append("      ,item_status = @itemStatus ");
                                SqlStringBuilder.Append("      ,dest_erp_warehouse = @destErpWarehouse ");
                                SqlStringBuilder.Append("      ,factory_id = @factoryId,factory_code = @factoryCode ");
                                SqlStringBuilder.Append("      ,enabled = @enabled,update_userid = @updateUserid ");
                                SqlStringBuilder.Append("      ,update_time = @updateTime ");
                                SqlStringBuilder.Append(" WHERE order_no = @orderNo and part_no = @partNo  ");

                                sqlList.Add(SqlStringBuilder.ToString());

                                parameters = new DynamicParameters();
                                parameters.Add("@orderNo", sapMiscosDetail.Zinstno);//销售交货单
                                parameters.Add("@itemNo", sapMiscosDetail.Zeile);// item

                                if (sysPart == null)
                                {
                                    parameters.Add("@partId", 0);//物料Id
                                    parameters.Add("@partSpec", "");//物料描述
                                }
                                else
                                {
                                    parameters.Add("@partId", sysPart.PartId);//物料Id
                                    parameters.Add("@partSpec", sysPart.PartSpec);//物料描述
                                }
                                parameters.Add("@partNo", sapMiscosDetail.Matnr);//物料编码
                                parameters.Add("@qty", sapMiscosDetail.SumErfmg);//交货数量
                                parameters.Add("@unit", sapMiscosDetail.Erfme);//单位

                                parameters.Add("@planDate", "");//计划交货日期
                                parameters.Add("@itemStatus", 10);//状态
                                parameters.Add("@destErpWarehouse", sapMiscosDetail.Lgort);//库存地

                                parameters.Add("@factoryId", sysFactory == null ? 0 : sysFactory.FactoryId);//工厂ID
                                parameters.Add("@factoryCode", sapMiscosDetail.Werks);//工厂代码
                                parameters.Add("@enabled", 'Y');//启用
                                parameters.Add("@updateUserid", 0);//修改人
                                parameters.Add("@updateTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));//修改日期
                                parametersList.Add(parameters);
                            }
                            else
                            {
                                SqlStringBuilder = new StringBuilder(1024);
                                SqlStringBuilder.Append("INSERT INTO dbo.wms_instock_detail(order_no,item_no,part_id,part_no,part_spec,qty,rec_qty,unit ");
                                SqlStringBuilder.Append("           ,plan_date,plan_time,item_status,dest_warehouse_id,dest_warehouse_name,dest_zone_id,dest_zone_name ");
                                SqlStringBuilder.Append("           ,dest_locate_id,dest_locate_name,dest_erp_warehouse,factory_id,factory_code,enabled ");
                                SqlStringBuilder.Append("           ,create_userid,create_time) ");
                                SqlStringBuilder.Append("     VALUES(@orderNo,@itemNo,@partId,@partNo,@partSpec,@qty,@recQty,@unit,@planDate ");
                                SqlStringBuilder.Append("           ,'',@itemStatus,0,'',0,'' ");
                                SqlStringBuilder.Append("           ,0,'',@destErpWarehouse,@factoryId,@factoryCode,@enabled ");
                                SqlStringBuilder.Append("           ,@createUserid,@createTime) ");
                                sqlList.Add(SqlStringBuilder.ToString());

                                parameters = new DynamicParameters();
                                parameters.Add("@orderNo", sapMiscosDetail.Zinstno);//销售交货单
                                parameters.Add("@itemNo", sapMiscosDetail.Zeile);//PO item

                                if (sysPart == null)
                                {
                                    parameters.Add("@partId", 0);//物料Id
                                    parameters.Add("@partSpec", "");//物料描述
                                }
                                else
                                {
                                    parameters.Add("@partId", sysPart.PartId);//物料Id
                                    parameters.Add("@partSpec", sysPart.PartSpec);//物料描述
                                }
                                parameters.Add("@partNo", sapMiscosDetail.Matnr);//物料编码

                                parameters.Add("@qty", sapMiscosDetail.SumErfmg);//交货数量
                                parameters.Add("@recQty", 0);//

                                parameters.Add("@unit", sapMiscosDetail.Erfme);//单位

                                parameters.Add("@planDate", "");//计划交货日期
                                parameters.Add("@itemStatus", 10);//状态
                                parameters.Add("@destErpWarehouse", sapMiscosDetail.Lgort);//库存地

                                parameters.Add("@factoryId", sysFactory == null ? 0 : sysFactory.FactoryId);//工厂ID
                                parameters.Add("@factoryCode", sapMiscosDetail.Werks);//工厂代码
                                parameters.Add("@enabled", 'Y');//启用
                                parameters.Add("@createUserid", 0);//创建人
                                parameters.Add("@createTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));//创建日期
                                parametersList.Add(parameters);
                            }
                        }
                        #endregion

                        #region 主表

                        SqlStringBuilder = new StringBuilder(1024);
                        SqlStringBuilder.Append("SELECT * FROM wms_instock (nolock) ");
                        SqlStringBuilder.Append("WHERE order_no = '" + sapMisco.Zinstno + "'");
                        List<WmsInstock> WmsInstockList = dbConn.Query<WmsInstock>(SqlStringBuilder.ToString()).ToList();
                        string guidStr = Guid.NewGuid().ToString();

                        SqlStringBuilder = new StringBuilder(1024);
                        SqlStringBuilder.Append("SELECT ZINSTNO,ZEILE,WERKS,LGORT,LGORT,MATNR,ERFME,SOBKZ,HTEXT,ZZLZT,ZACTION,ZACTION,DEPARTMENT,REFORDERNO FROM SAP_MISCO (nolock) WHERE ZINSTNO='" + sapMisco.Zinstno + "' AND SID ='" + sapMisco.Sid + "' AND ZZLZT='X' ");
                        SapMisco_Extend SapMiscomainDel = dbConn.Query<SapMisco_Extend>(SqlStringBuilder.ToString()).FirstOrDefault();

                        if (WmsInstockList.Count > 0)
                        {
                            if (SapMiscomainDel != null)
                            {
                                SqlStringBuilder = new StringBuilder(1024);
                                SqlStringBuilder.Append("UPDATE dbo.wms_instock ");
                                SqlStringBuilder.Append("   SET order_status = @orderStatus ");
                                SqlStringBuilder.Append("      ,update_userid = @updateUserid,update_time = @updateTime ");
                                SqlStringBuilder.Append(" WHERE order_no = @orderNo ");
                                sqlList.Add(SqlStringBuilder.ToString());

                                parameters = new DynamicParameters();
                                parameters.Add("@orderNo", SapMiscomainDel.Zinstno);//入库单号
                                parameters.Add("@orderStatus", 60);//状态 已生成
                                parameters.Add("@updateUserid", 0);//更新人
                                parameters.Add("@updateTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));//更新日期
                                parametersList.Add(parameters);
                            }
                        }

                        SqlStringBuilder = new StringBuilder(1024);
                        SqlStringBuilder.Append("SELECT ZINSTNO,ZEILE,WERKS,LGORT,LGORT,MATNR,ERFME,SOBKZ,HTEXT,ZZLZT,ZACTION FROM,DEPARTMENT,REFORDERNO SAP_MISCO (nolock) WHERE ZINSTNO='" + sapMisco.Zinstno + "' AND SID ='" + sapMisco.Sid + "' AND ZZLZT!='X' ");
                        SapMisco_Extend SapMiscomain = dbConn.Query<SapMisco_Extend>(SqlStringBuilder.ToString()).FirstOrDefault();

                        if (WmsInstockList.Count > 0)
                        {
                            if (SapMiscomain != null)
                            {
                                SqlStringBuilder = new StringBuilder(1024);
                                SqlStringBuilder.Append("UPDATE dbo.wms_instock ");
                                SqlStringBuilder.Append("   SET order_no = @orderNo,order_type = @orderType,order_status = @orderStatus ");
                                SqlStringBuilder.Append("      ,factory_id = @factoryId,factory_code = @factoryCode ");
                                SqlStringBuilder.Append("      ,enabled = @enabled,update_userid = @updateUserid,update_time = @updateTime ");
                                SqlStringBuilder.Append(" WHERE order_no = @orderNo ");
                                sqlList.Add(SqlStringBuilder.ToString());

                                parameters = new DynamicParameters();
                                parameters.Add("@orderNo", SapMiscomain.Zinstno);//
                                parameters.Add("@orderType", (int)WmsEnumUtil.InStockType.EXCEPTION_IN_STOCK);//类型 零星入库
                                parameters.Add("@orderStatus", (int)WmsEnumUtil.MoveOrderStatus.CREATE);//状态

                                SysFactory sysFactory = sysFactoryAll.Where(a => a.FactoryCode == SapMiscomain.Werks).FirstOrDefault();//工厂
                                parameters.Add("@factoryId", sysFactory == null ? 0 : sysFactory.FactoryId);//工厂ID
                                parameters.Add("@factoryCode", SapMiscomain.Werks);//工厂代码

                                parameters.Add("@enabled", 'Y');//启用
                                parameters.Add("@updateUserid", 0);//更新人
                                parameters.Add("@updateTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));//更新日期

                                parametersList.Add(parameters);
                            }
                        }
                        else
                        {
                            if (SapMiscomain != null)
                            {
                                SqlStringBuilder = new StringBuilder(1024);
                                SqlStringBuilder.Append("INSERT INTO dbo.wms_instock(order_no,order_type,order_status,vendor_id,vendor_code,customer_id, ");
                                SqlStringBuilder.Append("           ref_order_no,create_userid,customer_code,factory_id,factory_code,enabled,create_userid,create_time,guid) ");
                                SqlStringBuilder.Append("     VALUES(@orderNo,@orderType,@orderStatus,0,'',0,'',@ref_order_no,@create_userid, ");
                                SqlStringBuilder.Append("           ,@factoryId,@factoryCode,@enabled,@createUserid,@createTime,@guid) ");
                                sqlList.Add(SqlStringBuilder.ToString());

                                parameters = new DynamicParameters();
                                parameters.Add("@orderNo", SapMiscomain.Zinstno);//销售交货单
                                parameters.Add("@orderType", (int)WmsEnumUtil.InStockType.EXCEPTION_IN_STOCK);//类型 零星入库
                                parameters.Add("@orderStatus", (int)WmsEnumUtil.MoveOrderStatus.CREATE);//状态

                                SysFactory sysFactory = sysFactoryAll.Where(a => a.FactoryCode == SapMiscomain.Werks).FirstOrDefault();//工厂
                                parameters.Add("@factoryId", sysFactory == null ? 0 : sysFactory.FactoryId);//工厂ID
                                parameters.Add("@factoryCode", SapMiscomain.Werks);//工厂代码
                                parameters.Add("@ref_order_no", SapMiscomain.RefOrderNo);//关联订单
                                parameters.Add("@create_userid", SapMiscomain.DepartMent);//创建人
                                parameters.Add("@enabled", 'Y');//启用
                                parameters.Add("@createUserid", 0);//创建人
                                parameters.Add("@createTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));//创建日期
                                parameters.Add("@guid", guidStr);//guid

                                parametersList.Add(parameters);
                            }
                        }
                        #endregion
                    }
                    else if (sapMisco.Zaction.Trim() == "C00" || sapMisco.Zaction.Trim() == "C02" || sapMisco.Zaction.Trim() == "C04")//出库
                    {
                        #region 明细
                        SqlStringBuilder = new StringBuilder(1024);
                        SqlStringBuilder.Append("SELECT * FROM wms_outstock_detail (nolock) ");
                        SqlStringBuilder.Append("WHERE order_no = '" + sapMisco.Zinstno + "'");
                        List<WmsOutstockDetail> wmsOutstockDetailsList = dbConn.Query<WmsOutstockDetail>(SqlStringBuilder.ToString()).ToList();

                        SqlStringBuilder = new StringBuilder(1024);
                        SqlStringBuilder.Append("SELECT ZINSTNO,ZEILE,WERKS,LGORT,LGORT,MATNR,SUM(ERFMG) SumErfmg ,ERFME,SOBKZ,HTEXT,ZZLZT,ZACTION FROM SAP_MISCO (nolock) WHERE ZINSTNO='" + sapMisco.Zinstno + "' AND SID ='" + sapMisco.Sid + "' AND ZZLZT='X' ");
                        SqlStringBuilder.Append("	GROUP BY ZINSTNO,ZEILE,WERKS,LGORT,LGORT,MATNR,ERFME,SOBKZ,HTEXT,ZZLZT,ZACTION ");
                        List<SapMisco> sapMiscosDetailsDel = dbConn.Query<SapMisco>(SqlStringBuilder.ToString()).ToList();
                        //单据明细
                        foreach (SapMisco sapMiscosDel in sapMiscosDetailsDel)
                        {
                            WmsOutstockDetail WmsOutstockDetailInfo = wmsOutstockDetailsList.Where(a => a.OrderNo == sapMiscosDel.Zinstno && a.PartNo == sapMiscosDel.Matnr).FirstOrDefault();
                            if (WmsOutstockDetailInfo != null)
                            {
                                SqlStringBuilder = new StringBuilder(1024);
                                SqlStringBuilder.Append("UPDATE dbo.wms_outstock_detail ");
                                SqlStringBuilder.Append("   SET item_status=@itemStatus,qty = @qty ");
                                SqlStringBuilder.Append("      ,update_userid = @updateUserid,update_time = @updateTime ");
                                SqlStringBuilder.Append(" WHERE order_no = @orderNo and part_no=@partNo ");

                                sqlList.Add(SqlStringBuilder.ToString());

                                parameters = new DynamicParameters();
                                parameters.Add("@orderNo", sapMiscosDel.Zinstno);//单号
                                parameters.Add("@partNo", sapMiscosDel.Matnr);//物料编码
                                parameters.Add("@qty", 0);//物料编码
                                parameters.Add("@boxQty", 0);//物料编码
                                parameters.Add("@itemStatus", (int)WmsEnumUtil.PurchaseOrderDetailStatus.COMPLETED);//状态 已完成
                                parameters.Add("@updateUserid", 0);//创建人
                                parameters.Add("@updateTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));//创建日期
                                parametersList.Add(parameters);
                            }
                        }

                        SqlStringBuilder = new StringBuilder(1024);
                        SqlStringBuilder.Append("SELECT ZINSTNO,ZEILE,WERKS,LGORT,LGORT,MATNR,SUM(ERFMG) SumErfmg ,ERFME,SOBKZ,HTEXT,ZZLZT,ZACTION FROM SAP_MISCO (nolock) WHERE ZINSTNO='" + sapMisco.Zinstno + "' AND SID ='" + sapMisco.Sid + "' AND ZZLZT!='X' ");
                        SqlStringBuilder.Append("	GROUP BY ZINSTNO,ZEILE,WERKS,LGORT,LGORT,MATNR,ERFME,SOBKZ,HTEXT,ZZLZT,ZACTION ");
                        List<SapMisco> sapMiscosDetails = dbConn.Query<SapMisco>(SqlStringBuilder.ToString()).ToList();
                        //单据明细
                        foreach (SapMisco sapMiscosDetail in sapMiscosDetails)
                        {
                            SysFactory sysFactory = sysFactoryAll.Where(a => a.FactoryCode == sapMiscosDetail.Werks).FirstOrDefault();//工厂
                            SysPart sysPart = sysPartAll.Where(a => a.PartNo == sapMiscosDetail.Matnr).FirstOrDefault();//零件号ID

                            WmsOutstockDetail wmsOutstockDetailInfo = wmsOutstockDetailsList.Where(a => a.OrderNo == sapMiscosDetail.Zinstno && a.PartNo == sapMiscosDetail.Matnr).FirstOrDefault();
                            if (wmsOutstockDetailInfo != null)
                            {
                                SqlStringBuilder = new StringBuilder(1024);
                                SqlStringBuilder.Append("UPDATE dbo.wms_outstock_detail ");
                                SqlStringBuilder.Append("   SET item_no = @itemNo,part_id = @partId ");
                                SqlStringBuilder.Append("      ,part_no = @partNo,part_spec = @partSpec ");
                                SqlStringBuilder.Append("      ,qty = @qty,unit = @unit ");
                                SqlStringBuilder.Append("      ,plan_date = @planDate ");
                                SqlStringBuilder.Append("      ,item_status = @itemStatus ");
                                SqlStringBuilder.Append("      ,src_erp_warehouse = @srcErpWarehouse ");
                                SqlStringBuilder.Append("      ,factory_id = @factoryId,factory_code = @factoryCode ");
                                SqlStringBuilder.Append("      ,enabled = @enabled,update_userid = @updateUserid ");
                                SqlStringBuilder.Append("      ,update_time = @updateTime ");
                                SqlStringBuilder.Append(" WHERE order_no = @orderNo and part_no = @partNo  ");

                                sqlList.Add(SqlStringBuilder.ToString());

                                parameters = new DynamicParameters();
                                parameters.Add("@orderNo", sapMiscosDetail.Zinstno);//销售交货单
                                parameters.Add("@itemNo", sapMiscosDetail.Zeile);// item

                                if (sysPart == null)
                                {
                                    parameters.Add("@partId", 0);//物料Id
                                    parameters.Add("@partSpec", "");//物料描述
                                }
                                else
                                {
                                    parameters.Add("@partId", sysPart.PartId);//物料Id
                                    parameters.Add("@partSpec", sysPart.PartSpec);//物料描述
                                }
                                parameters.Add("@partNo", sapMiscosDetail.Matnr);//物料编码
                                parameters.Add("@qty", sapMiscosDetail.SumErfmg);//交货数量
                                parameters.Add("@unit", sapMiscosDetail.Erfme);//单位

                                parameters.Add("@planDate", "");//计划交货日期
                                parameters.Add("@itemStatus", 10);//状态
                                parameters.Add("@srcErpWarehouse", sapMiscosDetail.Lgort);//库存地

                                parameters.Add("@factoryId", sysFactory == null ? 0 : sysFactory.FactoryId);//工厂ID
                                parameters.Add("@factoryCode", sapMiscosDetail.Werks);//工厂代码
                                parameters.Add("@enabled", 'Y');//启用
                                parameters.Add("@updateUserid", 0);//修改人
                                parameters.Add("@updateTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));//修改日期
                                parametersList.Add(parameters);
                            }
                            else
                            {
                                SqlStringBuilder = new StringBuilder(1024);
                                SqlStringBuilder.Append("INSERT INTO dbo.wms_outstock_detail(order_no,item_no,part_id,part_no,part_spec,qty,pick_qty,out_qty,unit ");
                                SqlStringBuilder.Append("           ,plan_date,plan_time,item_status,src_warehouse_id,src_warehouse_name,src_zone_id,src_zone_name ");
                                SqlStringBuilder.Append("           ,src_locate_id,src_locate_name,src_erp_warehouse,factory_id,factory_code,enabled ");
                                SqlStringBuilder.Append("           ,create_userid,create_time) ");
                                SqlStringBuilder.Append("     VALUES(@orderNo,@itemNo,@partId,@partNo,@partSpec,@qty,@pickQty,@outQty,@unit,@planDate ");
                                SqlStringBuilder.Append("           ,'',@itemStatus,0,'',0,'' ");
                                SqlStringBuilder.Append("           ,0,'',@srcErpWarehouse,@factoryId,@factoryCode,@enabled ");
                                SqlStringBuilder.Append("           ,@createUserid,@createTime) ");
                                sqlList.Add(SqlStringBuilder.ToString());

                                parameters = new DynamicParameters();
                                parameters.Add("@orderNo", sapMiscosDetail.Zinstno);//销售交货单
                                parameters.Add("@itemNo", sapMiscosDetail.Zeile);//PO item

                                if (sysPart == null)
                                {
                                    parameters.Add("@partId", 0);//物料Id
                                    parameters.Add("@partSpec", "");//物料描述
                                }
                                else
                                {
                                    parameters.Add("@partId", sysPart.PartId);//物料Id
                                    parameters.Add("@partSpec", sysPart.PartSpec);//物料描述
                                }
                                parameters.Add("@partNo", sapMiscosDetail.Matnr);//物料编码

                                parameters.Add("@qty", sapMiscosDetail.SumErfmg);//交货数量
                                parameters.Add("@pickQty", 0);//
                                parameters.Add("@outQty", 0);//

                                parameters.Add("@unit", sapMiscosDetail.Erfme);//单位

                                parameters.Add("@planDate", "");//计划交货日期
                                parameters.Add("@itemStatus", 10);//状态
                                parameters.Add("@srcErpWarehouse", sapMiscosDetail.Lgort);//库存地

                                parameters.Add("@factoryId", sysFactory == null ? 0 : sysFactory.FactoryId);//工厂ID
                                parameters.Add("@factoryCode", sapMiscosDetail.Werks);//工厂代码
                                parameters.Add("@enabled", 'Y');//启用
                                parameters.Add("@createUserid", 0);//创建人
                                parameters.Add("@createTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));//创建日期
                                parametersList.Add(parameters);
                            }
                        }
                        #endregion

                        #region 主表

                        SqlStringBuilder = new StringBuilder(1024);
                        SqlStringBuilder.Append("SELECT * FROM wms_outstock (nolock) ");
                        SqlStringBuilder.Append("WHERE order_no = '" + sapMisco.Zinstno + "'");
                        List<WmsOutstock> wmsOutstockList = dbConn.Query<WmsOutstock>(SqlStringBuilder.ToString()).ToList();
                        string guidStr = Guid.NewGuid().ToString();

                        SqlStringBuilder = new StringBuilder(1024);
                        SqlStringBuilder.Append("SELECT ZINSTNO,ZEILE,WERKS,LGORT,LGORT,MATNR,ERFME,SOBKZ,HTEXT,ZZLZT,ZACTION FROM SAP_MISCO (nolock) WHERE ZINSTNO='" + sapMisco.Zinstno + "' AND SID ='" + sapMisco.Sid + "' AND ZZLZT='X' ");
                        SapMisco SapMiscomainDel = dbConn.Query<SapMisco>(SqlStringBuilder.ToString()).FirstOrDefault();

                        if (wmsOutstockList.Count > 0)
                        {
                            if (SapMiscomainDel != null)
                            {
                                SqlStringBuilder = new StringBuilder(1024);
                                SqlStringBuilder.Append("UPDATE dbo.wms_outstock ");
                                SqlStringBuilder.Append("   SET order_status = @orderStatus ");
                                SqlStringBuilder.Append("      ,update_userid = @updateUserid,update_time = @updateTime ");
                                SqlStringBuilder.Append(" WHERE order_no = @orderNo ");
                                sqlList.Add(SqlStringBuilder.ToString());

                                parameters = new DynamicParameters();
                                parameters.Add("@orderNo", SapMiscomainDel.Zinstno);//ASN号
                                parameters.Add("@orderStatus", 60);//状态 已生成
                                parameters.Add("@updateUserid", 0);//更新人
                                parameters.Add("@updateTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));//更新日期
                                parametersList.Add(parameters);
                            }
                        }

                        SqlStringBuilder = new StringBuilder(1024);
                        SqlStringBuilder.Append("SELECT ZINSTNO,ZEILE,WERKS,LGORT,LGORT,MATNR,ERFME,SOBKZ,HTEXT,ZZLZT,ZACTION FROM SAP_MISCO (nolock) WHERE ZINSTNO='" + sapMisco.Zinstno + "' AND SID ='" + sapMisco.Sid + "' AND ZZLZT!='X' ");
                        SapMisco_Extend SapMiscomain = dbConn.Query<SapMisco_Extend>(SqlStringBuilder.ToString()).FirstOrDefault();

                        if (wmsOutstockList.Count > 0)
                        {
                            if (SapMiscomain != null)
                            {
                                SqlStringBuilder = new StringBuilder(1024);
                                SqlStringBuilder.Append("UPDATE dbo.wms_outstock ");
                                SqlStringBuilder.Append("   SET order_no = @orderNo,order_type = @orderType,order_status = @orderStatus ");
                                SqlStringBuilder.Append("      ,factory_id = @factoryId,factory_code = @factoryCode ");
                                SqlStringBuilder.Append("      ,enabled = @enabled,update_userid = @updateUserid,update_time = @updateTime ");
                                SqlStringBuilder.Append(" WHERE order_no = @orderNo ");
                                sqlList.Add(SqlStringBuilder.ToString());

                                parameters = new DynamicParameters();
                                parameters.Add("@orderNo", SapMiscomain.Zinstno);//
                                parameters.Add("@orderType", (int)WmsEnumUtil.OutStockType.EXCEPTION_OUT_STOCK);//类型 零星出库
                                parameters.Add("@orderStatus", (int)WmsEnumUtil.MoveOrderStatus.CREATE);//状态

                                SysFactory sysFactory = sysFactoryAll.Where(a => a.FactoryCode == SapMiscomain.Werks).FirstOrDefault();//工厂
                                parameters.Add("@factoryId", sysFactory == null ? 0 : sysFactory.FactoryId);//工厂ID
                                parameters.Add("@factoryCode", SapMiscomain.Werks);//工厂代码

                                parameters.Add("@enabled", 'Y');//启用
                                parameters.Add("@updateUserid", 0);//更新人
                                parameters.Add("@updateTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));//更新日期

                                parametersList.Add(parameters);
                            }
                        }
                        else
                        {
                            if (SapMiscomain != null)
                            {
                                SqlStringBuilder = new StringBuilder(1024);
                                SqlStringBuilder.Append("INSERT INTO dbo.wms_outstock(order_no,order_type,order_status,vendor_id,vendor_code,customer_id ");
                                SqlStringBuilder.Append("           ,customer_code,factory_id,ref_order_no,create_userid,factory_code,enabled,create_userid,create_time,guid) ");
                                SqlStringBuilder.Append("     VALUES(@orderNo,@orderType,@orderStatus,0,'',0,'' ");
                                SqlStringBuilder.Append("           ,@factoryId,@ref_order_no,@create_userid,@factoryCode,@enabled,@createUserid,@createTime,@guid) ");
                                sqlList.Add(SqlStringBuilder.ToString());

                                parameters = new DynamicParameters();
                                parameters.Add("@orderNo", SapMiscomain.Zinstno);//销售交货单
                                parameters.Add("@orderType", (int)WmsEnumUtil.OutStockType.EXCEPTION_OUT_STOCK);//类型 零星出库
                                parameters.Add("@orderStatus", (int)WmsEnumUtil.MoveOrderStatus.CREATE);//状态

                                SysFactory sysFactory = sysFactoryAll.Where(a => a.FactoryCode == SapMiscomain.Werks).FirstOrDefault();//工厂
                                parameters.Add("@factoryId", sysFactory == null ? 0 : sysFactory.FactoryId);//工厂ID
                                parameters.Add("@ref_order_no", SapMiscomain.RefOrderNo);//关联订单
                                parameters.Add("@create_userid", SapMiscomain.DepartMent);//创建人
                                parameters.Add("@factoryCode", SapMiscomain.Werks);//工厂代码
                                parameters.Add("@enabled", 'Y');//启用
                                parameters.Add("@createUserid", 0);//创建人
                                parameters.Add("@createTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));//创建日期
                                parameters.Add("@guid", guidStr);//guid

                                parametersList.Add(parameters);
                            }
                        }
                        #endregion
                    }

                    SqlStringBuilder = new StringBuilder(1024);
                    SqlStringBuilder.Append("update SAP_MISCO set SYNFLG='Y',SYNTIM=@SYNTIM  where ZINSTNO=@ZINSTNO AND SID=@SID ");//更新同步状态
                    sqlList.Add(SqlStringBuilder.ToString());

                    parameters = new DynamicParameters();
                    parameters.Add("@ZINSTNO", sapMisco.Zinstno);//ZINSTNO
                    parameters.Add("@SID", sapMisco.Sid);//sid
                    parameters.Add("@SYNTIM", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));//同步时间
                    parametersList.Add(parameters);

                    bool staResult = ExecuteTransaction(sqlList, parametersList);
                    if (staResult == false)
                    {
                        sqlList = new List<string>();
                        parametersList = new List<DynamicParameters>();
                        SqlStringBuilder = new StringBuilder(1024);
                        SqlStringBuilder.Append("update SAP_MISCO set SYNFLG='E',ERRMSG=@ERRMSG,SYNTIM=@SYNTIM  where ZINSTNO=@ZINSTNO AND SID=@SID ");//更新同步状态
                        sqlList.Add(SqlStringBuilder.ToString());

                        parameters = new DynamicParameters();
                        parameters.Add("@ZINSTNO", sapMisco.Zinstno);//ZINSTNO
                        parameters.Add("@SID", sapMisco.Sid);//sid
                        parameters.Add("@ERRMSG", "同步错误，请检查接口数据！");//错误
                        parameters.Add("@SYNTIM", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));//同步时间
                        parametersList.Add(parameters);
                        ExecuteTransaction(sqlList, parametersList);
                        return false;
                    }
                }

                return true;
            }
        }
        #endregion

        #region 盘点

        /// <summary>
        /// 获取盘点开始时，SAP冻结库存，并把盘点表传到WMS
        /// </summary>
        /// <returns></returns>
        public List<SapCyco> GetInventoryListInfo()
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                StringBuilder sql = new StringBuilder(1024);
                sql.Append("SELECT top 1000 IBLNR,COUNT(1),SID,LGORT,WERKS FROM sap_cyco (nolock) ");
                sql.Append("WHERE  SYNFLG = 'N' ");
                sql.Append("GROUP BY IBLNR,SID,LGORT,WERKS ");

                return dbConn.Query<SapCyco>(sql.ToString()).ToList();
            }
        }

        /// <summary>
        /// 添加盘点开始时，SAP冻结库存，并把盘点表传到WMS
        /// </summary>
        /// <param name="sapCu"></param>
        /// <returns></returns>
        public bool InsertInventoryListInfo(List<SapCyco> sapCycos)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                StringBuilder stringBuilder = new StringBuilder();
                StringBuilder SqlStringBuilder = new StringBuilder(1024);
                DynamicParameters parameters = new DynamicParameters();

                StringBuilder factoryStringBuilder = new StringBuilder(1024);
                factoryStringBuilder.Append("select * from sys_factory (nolock) where enabled='Y'");//工厂
                List<SysFactory> sysFactoryAll = dbConn.Query<SysFactory>(factoryStringBuilder.ToString()).ToList();

                StringBuilder partNoStringBuilder = new StringBuilder(1024);
                partNoStringBuilder.Append("select * from sys_part (nolock) where enabled='Y' ");//零件号
                List<SysPart> sysPartAll = dbConn.Query<SysPart>(partNoStringBuilder.ToString()).ToList();

                SapCyco sapCyco = new SapCyco();
                for (int i = 0; i < sapCycos.Count; i++)
                {
                    List<string> sqlList = new List<string>();
                    List<DynamicParameters> parametersList = new List<DynamicParameters>();
                    sapCyco = sapCycos[i];

                    SqlStringBuilder = new StringBuilder(1024);
                    SqlStringBuilder.Append("SELECT IBLNR,ZEILI,MATNR,MEINS,WERKS,LGORT,ZSTAT,SOBKZ,XBUFI,LSTAT,GJAHR FROM SAP_CYCO (nolock) WHERE IBLNR='" + sapCyco.Iblnr + "' AND SID ='" + sapCyco.Sid + "' AND (LSTAT!='X' or LSTAT is null )");
                    List<SapCyco> sapCycoPartList = dbConn.Query<SapCyco>(SqlStringBuilder.ToString()).ToList();
                    if (sapCycoPartList.Count > 0)
                    {
                        stringBuilder = new StringBuilder();
                        stringBuilder.Append(" SELECT * from sys_zone (nolock) WHERE erp_warehouse='" + sapCyco.Lgort + "'");
                        List<SysZone> sysZones = dbConn.Query<SysZone>(stringBuilder.ToString()).ToList();
                        SysFactory sysFactory = sysFactoryAll.Where(a => a.FactoryCode == sapCyco.Werks).FirstOrDefault();//工厂

                        for (int k = 0; k < sysZones.Count; k++)
                        {
                            stringBuilder = new StringBuilder();
                            stringBuilder.Append(" SELECT * from wms_check_stock_zone (nolock) WHERE order_no='" + sapCyco.Iblnr + "' and zone_name='" + sysZones[k].ZoneName + "'");
                            List<WmsCheckStockZone> checkStockZones = dbConn.Query<WmsCheckStockZone>(stringBuilder.ToString()).ToList();
                            if (checkStockZones.Count == 0)
                            {
                                SqlStringBuilder = new StringBuilder(1024);
                                SqlStringBuilder.Append("INSERT INTO dbo.wms_check_stock_zone(order_no,zone_id,zone_name,factory_id,factory_code,enabled,create_userid,create_time,guid) ");
                                SqlStringBuilder.Append("     VALUES(@orderNo,@zoneId,@zoneName,@factoryId,@factoryCode,'Y',@createUserid,CONVERT(varchar(50), GETDATE(), 21),NEWID()) ");
                                sqlList.Add(SqlStringBuilder.ToString());
                                parameters = new DynamicParameters();
                                parameters.Add("@orderNo", sapCyco.Iblnr);
                                parameters.Add("@zoneId", sysZones[k].ZoneId);
                                parameters.Add("@zoneName", sysZones[k].ZoneName);
                                parameters.Add("@factoryId", sysFactory == null ? 0 : sysFactory.FactoryId);//工厂ID
                                parameters.Add("@factoryCode", sapCyco.Werks);//工厂代码
                                parameters.Add("@enabled", "Y");
                                parameters.Add("@createUserid", 0);
                                parametersList.Add(parameters);
                            }


                            for (int p = 0; p < sapCycoPartList.Count; p++)
                            {
                                SysPart sysPart = sysPartAll.Where(a => a.PartNo == sapCycoPartList[p].Matnr).FirstOrDefault();//零件号ID

                                stringBuilder = new StringBuilder();
                                stringBuilder.Append(" SELECT * from wms_check_stock_range (nolock) WHERE order_no='" + sapCycoPartList[p].Iblnr + "' and zone_name='" + sysZones[k].ZoneName + "' and part_no='" + sapCycoPartList[p].Matnr + "'");
                                List<WmsCheckStockRange> checkStockRanges = dbConn.Query<WmsCheckStockRange>(stringBuilder.ToString()).ToList();
                                if (checkStockRanges.Count == 0)
                                {
                                    SqlStringBuilder = new StringBuilder(1024);
                                    SqlStringBuilder.Append("INSERT INTO dbo.wms_check_stock_range(order_no,zone_id,zone_name,locate_id,locate_name,part_id,part_no,part_spec,factory_id,factory_code,enabled,create_userid,create_time,guid) ");
                                    SqlStringBuilder.Append("     VALUES(@orderNo,@zoneId,@zoneName,@locateId,@locateName,@partId,@partNo,@partSpec,@factoryId,@factoryCode,'Y',@createUserid ");
                                    SqlStringBuilder.Append("           ,CONVERT(varchar(50), GETDATE(), 21),NEWID()) ");
                                    sqlList.Add(SqlStringBuilder.ToString());
                                    parameters = new DynamicParameters();
                                    parameters.Add("@orderNo", sapCycoPartList[p].Iblnr);
                                    parameters.Add("@zoneId", sysZones[k].ZoneId);
                                    parameters.Add("@zoneName", sysZones[k].ZoneName);
                                    parameters.Add("@locateId", 0);
                                    parameters.Add("@locateName", "");
                                    parameters.Add("@partId", sysPart.PartId);
                                    parameters.Add("@partNo", sysPart.PartNo);
                                    parameters.Add("@partSpec", sysPart.PartSpec);
                                    parameters.Add("@factoryId", sysFactory == null ? 0 : sysFactory.FactoryId);//工厂ID
                                    parameters.Add("@factoryCode", sapCycoPartList[p].Werks);//工厂代码
                                    parameters.Add("@enabled", "Y");
                                    parameters.Add("@createUserid", 0);
                                    parametersList.Add(parameters);
                                }
                            }
                        }

                        for (int p = 0; p < sapCycoPartList.Count; p++)
                        {
                            SysPart sysPart = sysPartAll.Where(a => a.PartNo == sapCycoPartList[p].Matnr).FirstOrDefault();//零件号ID

                            SqlStringBuilder = new StringBuilder(1024);
                            SqlStringBuilder.Append("INSERT INTO dbo.wms_check_stock_part(order_no,part_id,part_no,part_spec,factory_id,factory_code ");
                            SqlStringBuilder.Append("           ,enabled,create_userid,create_time,guid) ");
                            SqlStringBuilder.Append("     VALUES(@orderNo,@partId,@partNo,@partSpec,@factoryId,@factoryCode,@enabled, ");
                            SqlStringBuilder.Append("	       @createUserid,CONVERT(varchar(50), GETDATE(), 21),NEWID()) ");
                            sqlList.Add(SqlStringBuilder.ToString());
                            parameters = new DynamicParameters();
                            parameters.Add("@orderNo", sapCycoPartList[p].Iblnr);
                            if (sysPart == null)
                            {
                                parameters.Add("@partId", 0);//物料Id
                                parameters.Add("@partSpec", "");//物料描述
                            }
                            else
                            {
                                parameters.Add("@partId", sysPart.PartId);//物料Id
                                parameters.Add("@partSpec", sysPart.PartSpec);//物料描述
                            }
                            parameters.Add("@partNo", sapCycoPartList[p].Matnr);//物料编码
                            parameters.Add("@factoryId", sysFactory == null ? 0 : sysFactory.FactoryId);//工厂ID
                            parameters.Add("@factoryCode", sapCycoPartList[p].Werks);//工厂代码
                            parameters.Add("@enabled", "Y");
                            parameters.Add("@createUserid", 0);
                            parametersList.Add(parameters);
                        }
                    }

                    SqlStringBuilder = new StringBuilder(1024);
                    SqlStringBuilder.Append("SELECT * FROM wms_check_stock (nolock) ");
                    SqlStringBuilder.Append("WHERE order_no = '" + sapCyco.Iblnr + "'");
                    List<WmsPurchase> wmsPurchaseList = dbConn.Query<WmsPurchase>(SqlStringBuilder.ToString()).ToList();
                    string guidStr = Guid.NewGuid().ToString();

                    SqlStringBuilder = new StringBuilder(1024);
                    SqlStringBuilder.Append("SELECT IBLNR,ZEILI,MATNR,MEINS,WERKS,LGORT,ZSTAT,SOBKZ,XBUFI,LSTAT,GJAHR FROM SAP_CYCO (nolock) WHERE IBLNR='" + sapCyco.Iblnr + "' AND SID ='" + sapCyco.Sid + "' AND LSTAT='X' ");
                    SapCyco sapCycomainDel = dbConn.Query<SapCyco>(SqlStringBuilder.ToString()).FirstOrDefault();
                    if (wmsPurchaseList.Count > 0)
                    {
                        if (sapCycomainDel != null)
                        {
                            SqlStringBuilder = new StringBuilder(1024);
                            SqlStringBuilder.Append("UPDATE dbo.wms_check_stock ");
                            SqlStringBuilder.Append("   SET order_status = @orderStatus ");
                            SqlStringBuilder.Append("      ,update_userid = @updateUserid,update_time = @updateTime ");
                            SqlStringBuilder.Append(" WHERE order_no = @orderNo ");
                            sqlList.Add(SqlStringBuilder.ToString());

                            parameters = new DynamicParameters();
                            parameters.Add("@orderNo", sapCycomainDel.Iblnr);//盘点单号
                            parameters.Add("@orderStatus", (int)WmsEnumUtil.MoveOrderStatus.CANCEL);//状态 已取消
                            parameters.Add("@updateUserid", 0);//更新人
                            parameters.Add("@updateTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));//更新日期
                            parametersList.Add(parameters);
                        }
                    }

                    SqlStringBuilder = new StringBuilder(1024);
                    SqlStringBuilder.Append("SELECT IBLNR,ZEILI,MATNR,MEINS,WERKS,LGORT,ZSTAT,SOBKZ,XBUFI,LSTAT,GJAHR FROM SAP_CYCO (nolock) WHERE IBLNR='" + sapCyco.Iblnr + "' AND SID ='" + sapCyco.Sid + "' AND (LSTAT!='X' or LSTAT is null) ");
                    SapCyco sapCycomain = dbConn.Query<SapCyco>(SqlStringBuilder.ToString()).FirstOrDefault();
                    if (wmsPurchaseList.Count > 0)
                    {
                        if (sapCycomain != null)
                        {
                            SqlStringBuilder = new StringBuilder(1024);
                            SqlStringBuilder.Append("UPDATE dbo.wms_check_stock ");
                            SqlStringBuilder.Append("   SET order_no = @orderNo,part_no = @partNo,erp_warehouse = @erpWarehouse,order_type = @orderType ");
                            SqlStringBuilder.Append("      ,order_status = @orderStatus,is_obvious = @isObvious,enabled = @enabled ");
                            SqlStringBuilder.Append("      ,factory_id = @factoryId,factory_code = @factoryCode,update_userid = @updateUserid,update_time = @updateTime ");
                            SqlStringBuilder.Append(" WHERE order_no = @orderNo ");

                            sqlList.Add(SqlStringBuilder.ToString());

                            parameters = new DynamicParameters();
                            parameters.Add("@orderNo", sapCycomain.Iblnr);//盘点单号
                            parameters.Add("@partNo", sapCycomain.Matnr);//物料编码
                            parameters.Add("@erpWarehouse", sapCycomain.Lgort);//库存地
                            parameters.Add("@orderType", 10);//类型
                            parameters.Add("@orderStatus", (int)WmsEnumUtil.MoveOrderStatus.CREATE);//状态
                            parameters.Add("@isObvious", 1);//盘点类型 明盘

                            SysFactory sysFactory = sysFactoryAll.Where(a => a.FactoryCode == sapCycomain.Werks).FirstOrDefault();//工厂
                            parameters.Add("@factoryId", sysFactory == null ? 0 : sysFactory.FactoryId);//工厂ID
                            parameters.Add("@factoryCode", sapCycomain.Werks);//工厂代码

                            parameters.Add("@enabled", 'Y');//启用
                            parameters.Add("@updateUserid", 0);//更新人
                            parameters.Add("@updateTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));//更新日期
                            parametersList.Add(parameters);
                        }
                    }
                    else
                    {
                        if (sapCycomain != null)
                        {
                            SqlStringBuilder = new StringBuilder(1024);
                            SqlStringBuilder.Append("INSERT INTO dbo.wms_check_stock(order_no,part_no,erp_warehouse,order_type,order_status,is_obvious ");
                            SqlStringBuilder.Append("           ,enabled,factory_id,factory_code,create_userid,create_time,guid) ");
                            SqlStringBuilder.Append("     VALUES(@orderNo,@partNo,@erpWarehouse,@orderType,@orderStatus,@isObvious,@enabled ");
                            SqlStringBuilder.Append("           ,@factoryId,@factoryCode,@createUserid,@createTime,NEWID()) ");
                            sqlList.Add(SqlStringBuilder.ToString());

                            parameters = new DynamicParameters();
                            parameters.Add("@orderNo", sapCycomain.Iblnr);//盘点单号
                            parameters.Add("@partNo", sapCycomain.Matnr);//物料编码
                            parameters.Add("@erpWarehouse", sapCycomain.Lgort);//库存地
                            parameters.Add("@orderType", 10);//类型 静态盘点
                            parameters.Add("@orderStatus", (int)WmsEnumUtil.MoveOrderStatus.CREATE);//状态
                            parameters.Add("@isObvious", 1);//盘点类型 明盘

                            SysFactory sysFactory = sysFactoryAll.Where(a => a.FactoryCode == sapCycomain.Werks).FirstOrDefault();//工厂
                            parameters.Add("@factoryId", sysFactory == null ? 0 : sysFactory.FactoryId);//工厂ID
                            parameters.Add("@factoryCode", sapCycomain.Werks);//工厂代码
                            parameters.Add("@enabled", 'Y');//启用
                            parameters.Add("@createUserid", 0);//更新人
                            parameters.Add("@createTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));//更新日期
                            parametersList.Add(parameters);
                        }
                    }


                    SqlStringBuilder = new StringBuilder(1024);
                    SqlStringBuilder.Append("update SAP_CYCO set SYNFLG='Y',SYNTIM=@SYNTIM  where IBLNR=@IBLNR AND SID=@SID ");//更新同步状态
                    sqlList.Add(SqlStringBuilder.ToString());

                    parameters = new DynamicParameters();
                    parameters.Add("@IBLNR", sapCyco.Iblnr);//盘点单号
                    parameters.Add("@SID", sapCyco.Sid);//ID
                    parameters.Add("@SYNTIM", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));//同步时间
                    parametersList.Add(parameters);

                    List<string> sqlDetailList = new List<string>();
                    List<DynamicParameters> parametersDetailList = new List<DynamicParameters>();
                    bool staResult = ExecuteTransaction(sqlList, parametersList);
                    if (staResult == false)
                    {
                        sqlList = new List<string>();
                        parametersList = new List<DynamicParameters>();
                        SqlStringBuilder = new StringBuilder(1024);
                        SqlStringBuilder.Append("update SAP_CYCO set SYNFLG='E',ERRMSG=@ERRMSG,SYNTIM=@SYNTIM  where IBLNR=@IBLNR AND SID=@SID ");//更新同步状态
                        sqlList.Add(SqlStringBuilder.ToString());

                        parameters = new DynamicParameters();
                        parameters.Add("@IBLNR", sapCyco.Iblnr);//盘点单号
                        parameters.Add("@SID", sapCyco.Sid);//ID
                        parameters.Add("@ERRMSG", "同步错误，请检查接口数据！");//错误
                        parameters.Add("@SYNTIM", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));//同步时间
                        parametersList.Add(parameters);
                        ExecuteTransaction(sqlList, parametersList);

                        return false;
                    }
                }

                return true;
            }
        }

        /// <summary>
        /// 获取盘点开始时，SAP冻结库存，并把盘点表传到WMS
        /// </summary>
        /// <returns></returns>
        public List<SapDifo> GetInventoryDifferenceAdjustmentInfo()
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                StringBuilder sql = new StringBuilder(1024);
                sql.Append("SELECT top 1000 * FROM sap_difo (nolock) ");
                sql.Append("WHERE  SYNFLG = 'N' ");
                sql.Append("ORDER BY RECTIM  ");

                return dbConn.Query<SapDifo>(sql.ToString()).ToList();
            }
        }

        /// <summary>
        /// 添加盘点开始时，SAP冻结库存，并把盘点表传到WMS
        /// </summary>
        /// <param name="sapCu"></param>
        /// <returns></returns>
        public bool InsertInventoryDifferenceAdjustmentInfo(List<SapDifo> sapDifos)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                StringBuilder stringBuilder = new StringBuilder();
                StringBuilder SqlStringBuilder = new StringBuilder(1024);
                DynamicParameters parameters = new DynamicParameters();

                SapDifo sapDifo = new SapDifo();
                for (int i = 0; i < sapDifos.Count; i++)
                {
                    List<string> sqlList = new List<string>();
                    List<DynamicParameters> parametersList = new List<DynamicParameters>();
                    sapDifo = sapDifos[i];
                    SqlStringBuilder = new StringBuilder(1024);
                    SqlStringBuilder.Append(" select a.* from sap_cyco a (nolock) left join sap_difo b (nolock) on a.IBLNR=b.IBLNR  and a.ZEILI=b.ZEILI where b.IBLNR='" + sapDifo.Iblnr + "' and b.ZEILI=" + sapDifo.Zeili + " ");
                    List<SapCyco> sapCycos = dbConn.Query<SapCyco>(SqlStringBuilder.ToString()).ToList();
                    if (sapCycos.Count > 0)
                    {
                        if (sapDifo.Ztzbs == "1")//正常调整
                        {
                            SqlStringBuilder = new StringBuilder(1024);
                            SqlStringBuilder.Append("select b.*,a.fact_qty,a.dest_warehouse_id,a.dest_warehouse_name,a.dest_zone_id,a.dest_zone_name" +
                                ",a.dest_locate_id,a.dest_locate_name,c.locate_type,d.erp_warehouse as dest_erp_warehouse from [dbo].[wms_check_stock_list] a (nolock) LEFT JOIN dbo.sys_stock b (nolock) ON a.carton_no=b.carton_no " +
                                " LEFT JOIN dbo.sys_locate c (nolock) ON a.dest_locate_id=c.locate_id" +
                                " LEFT JOIN dbo.sys_zone d (nolock) ON a.dest_zone_id=d.zone_id where a.order_no='" + sapDifo.Iblnr + "' and b.part_no='" + sapCycos[0].Matnr + "' and  a.fact_qty!=0 ");
                            List<SysStock> sysStocks = dbConn.Query<SysStock>(SqlStringBuilder.ToString()).ToList();

                            SqlStringBuilder = new StringBuilder(1024);
                            SqlStringBuilder.Append(" UPDATE dbo.wms_check_stock SET order_status = @orderStatus,update_userid=0, update_time = CONVERT(varchar(50), GETDATE(), 21) ");
                            SqlStringBuilder.Append("         WHERE order_no = @orderNo; ");
                            sqlList.Add(SqlStringBuilder.ToString());
                            parameters = new DynamicParameters();
                            parameters.Add("@orderStatus", 50);//
                            parameters.Add("@orderNo", sapDifo.Iblnr);
                            parametersList.Add(parameters);

                            for (int j = 0; j < sysStocks.Count; j++)
                            {
                                if (sysStocks[j].FactQty != 0 && sysStocks[j].TransStatus != 10)
                                {

                                    int statusNew = 50;//已入库
                                    if (sysStocks[j].LocateType == (int)WmsEnumUtil.LocateType.BASICS_LOCATE ||
                                        sysStocks[j].LocateType == (int)WmsEnumUtil.LocateType.MANEUVER_LOCATE ||
                                        sysStocks[j].LocateType == (int)WmsEnumUtil.LocateType.COMBINATION_LOCATE)
                                    {
                                        statusNew = (int)WmsEnumUtil.StockStatus.INSTOCKED;//已入库
                                    }
                                    else if (sysStocks[j].LocateType == (int)WmsEnumUtil.LocateType.LINE_LOCATE)//线边库位
                                    {
                                        statusNew = (int)WmsEnumUtil.StockStatus.ONLINED;
                                    }
                                    else if (sysStocks[j].LocateType == (int)WmsEnumUtil.LocateType.NC_LOCATE)//NC库位
                                    {
                                        statusNew = (int)WmsEnumUtil.StockStatus.NC_INSTOCK;
                                    }

                                    SqlStringBuilder = new StringBuilder(1024);
                                    SqlStringBuilder.Append(" UPDATE sys_stock SET qty=@qty,status=@status" +
                                        ",warehouse_id=@warehouseId,warehouse_name=@warehouseName," +
                                        " zone_id=@zoneId,zone_name=@zoneName" +
                                        ",locate_id=@locateId,locate_name=@locateName,erp_warehouse=@erpWarehouse," +
                                        "enabled='Y',update_userid=0, update_time = CONVERT(varchar(50), GETDATE(), 21) ");
                                    SqlStringBuilder.Append("         WHERE carton_no = @cartonNo; ");
                                    sqlList.Add(SqlStringBuilder.ToString());

                                    parameters = new DynamicParameters();
                                    parameters.Add("@qty", sysStocks[j].FactQty);//盘点更新
                                    parameters.Add("@status", statusNew);
                                    parameters.Add("@warehouseId", sysStocks[j].DestWarehouseId);
                                    parameters.Add("@warehouseName", sysStocks[j].DestWarehouseName);
                                    parameters.Add("@zoneId", sysStocks[j].DestZoneId);
                                    parameters.Add("@zoneName", sysStocks[j].DestLocateName);
                                    parameters.Add("@locateId", sysStocks[j].DestLocateId);
                                    parameters.Add("@locateName", sysStocks[j].DestLocateName);
                                    parameters.Add("@erpWarehouse", sysStocks[j].DestErpWarehouse);
                                    parameters.Add("@cartonNo", sysStocks[j].CartonNo);
                                    parametersList.Add(parameters);


                                    SqlStringBuilder = new StringBuilder(1024);
                                    SqlStringBuilder.Append(" INSERT INTO dbo.sys_stock_trans (trans_code, carton_no, part_id,part_no, part_spec,src_locate_id, src_locate_name,  ");
                                    SqlStringBuilder.Append("            dest_locate_id,dest_locate_name,old_qty, new_qty,trans_qty,old_status,new_status,unit,factory_id,factory_code,  ");
                                    SqlStringBuilder.Append("            src_erp_warehouse,dest_erp_warehouse, src_warehouse_id,src_warehouse_name,dest_warehouse_id,dest_warehouse_name,  ");
                                    SqlStringBuilder.Append("            src_zone_id,src_zone_name,dest_zone_id, dest_zone_name,enabled,create_userid,create_time,guid) ");
                                    SqlStringBuilder.Append("VALUES(@transCode, @cartonNo, @partId,@partNo, @partSpec,@srcLocateId, @srcLocateName,  ");
                                    SqlStringBuilder.Append("            @destLocateId,@destLocateName,@oldQty, @newQty,@transQty,@oldStatus,@newStatus,@unit,@factoryId,@factoryCode,  ");
                                    SqlStringBuilder.Append("            @srcErpWarehouse,@destErpWarehouse, @srcWarehouseId,@srcWarehouseName,@destWarehouseId,@destWarehouseName,  ");
                                    SqlStringBuilder.Append("             @srcZoneId,@srcZoneName,@destZoneId, @destZoneName,@enabled,@createUserid,@createTime,@guid) ");
                                    sqlList.Add(SqlStringBuilder.ToString());

                                    parameters = new DynamicParameters();
                                    parameters.Add("@transCode", 270);//盘点更新
                                    parameters.Add("@cartonNo", sysStocks[j].CartonNo);
                                    parameters.Add("@partId", sysStocks[j].PartId);
                                    parameters.Add("@partNo", sysStocks[j].PartNo);
                                    parameters.Add("@partSpec", sysStocks[j].PartSpec);
                                    parameters.Add("@srcLocateId", sysStocks[j].LocateId);//源库位
                                    parameters.Add("@srcLocateName", sysStocks[j].LocateName);
                                    parameters.Add("@destLocateId", sysStocks[j].LocateId);//目标库位
                                    parameters.Add("@destLocateName", sysStocks[j].LocateName);
                                    parameters.Add("@oldQty", sysStocks[j].Qty);
                                    parameters.Add("@newQty", sysStocks[j].FactQty);
                                    parameters.Add("@transQty", sysStocks[j].FactQty);
                                    parameters.Add("@oldStatus", sysStocks[j].Status);
                                    parameters.Add("@newStatus", sysStocks[j].Status);
                                    parameters.Add("@unit", sysStocks[j].Unit);
                                    parameters.Add("@factoryId", sysStocks[j].FactoryId);
                                    parameters.Add("@factoryCode", sysStocks[j].FactoryCode);
                                    parameters.Add("@srcErpWarehouse", sysStocks[j].ErpWarehouse);
                                    parameters.Add("@destErpWarehouse", sysStocks[j].ErpWarehouse);
                                    parameters.Add("@srcWarehouseId", sysStocks[j].WarehouseId);
                                    parameters.Add("@srcWarehouseName", sysStocks[j].WarehouseName);
                                    parameters.Add("@destWarehouseId", sysStocks[j].WarehouseId);
                                    parameters.Add("@destWarehouseName", sysStocks[j].WarehouseName);
                                    parameters.Add("@srcZoneId", sysStocks[j].ZoneId);
                                    parameters.Add("@srcZoneName", sysStocks[j].ZoneName);
                                    parameters.Add("@destZoneId", sysStocks[j].ZoneId);
                                    parameters.Add("@destZoneName", sysStocks[j].ZoneName);
                                    parameters.Add("@enabled", "Y");
                                    parameters.Add("@createUserid", 0);
                                    parameters.Add("@createTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                                    parameters.Add("@guid", Guid.NewGuid().ToString());
                                    parametersList.Add(parameters);
                                }

                            }

                        }
                        else //无差异，不调整
                        {
                            SqlStringBuilder = new StringBuilder(1024);
                            SqlStringBuilder.Append("select b.*,a.fact_qty from [dbo].[wms_check_stock_list] a (nolock) LEFT JOIN dbo.sys_stock b (nolock) ON a.carton_no=b.carton_no  where order_no='" + sapDifo.Iblnr + "' and  a.fact_qty!=0 ");
                            List<SysStock> sysStocks = dbConn.Query<SysStock>(SqlStringBuilder.ToString()).ToList();

                            SqlStringBuilder = new StringBuilder(1024);
                            SqlStringBuilder.Append(" UPDATE dbo.wms_check_stock SET order_status = @orderStatus,update_userid=0, update_time = CONVERT(varchar(50), GETDATE(), 21) ");
                            SqlStringBuilder.Append("         WHERE order_no = @orderNo; ");
                            sqlList.Add(SqlStringBuilder.ToString());
                            parameters = new DynamicParameters();
                            parameters.Add("@orderStatus", 50);//
                            parameters.Add("@orderNo", sapDifo.Iblnr);
                            parametersList.Add(parameters);

                            for (int j = 0; j < sysStocks.Count; j++)
                            {
                                SqlStringBuilder = new StringBuilder(1024);
                                SqlStringBuilder.Append(" UPDATE sys_stock SET  enabled='Y' ,update_userid=0, update_time = CONVERT(varchar(50), GETDATE(), 21) ");
                                SqlStringBuilder.Append("         WHERE carton_no = @cartonNo; ");
                                sqlList.Add(SqlStringBuilder.ToString());
                                parameters = new DynamicParameters();
                                parameters.Add("@cartonNo", sysStocks[j].CartonNo);
                                parametersList.Add(parameters);

                                SqlStringBuilder = new StringBuilder(1024);
                                SqlStringBuilder.Append(" INSERT INTO dbo.sys_stock_trans (trans_code, carton_no, part_id,part_no, part_spec,src_locate_id, src_locate_name,  ");
                                SqlStringBuilder.Append("            dest_locate_id,dest_locate_name,old_qty, new_qty,trans_qty,old_status,new_status,unit,factory_id,factory_code,  ");
                                SqlStringBuilder.Append("            src_erp_warehouse,dest_erp_warehouse, src_warehouse_id,src_warehouse_name,dest_warehouse_id,dest_warehouse_name,  ");
                                SqlStringBuilder.Append("            src_zone_id,src_zone_name,dest_zone_id, dest_zone_name,enabled,create_userid,create_time,guid) ");
                                SqlStringBuilder.Append("VALUES(@transCode, @cartonNo, @partId,@partNo, @partSpec,@srcLocateId, @srcLocateName,  ");
                                SqlStringBuilder.Append("            @destLocateId,@destLocateName,@oldQty, @newQty,@transQty,@oldStatus,@newStatus,@unit,@factoryId,@factoryCode,  ");
                                SqlStringBuilder.Append("            @srcErpWarehouse,@destErpWarehouse, @srcWarehouseId,@srcWarehouseName,@destWarehouseId,@destWarehouseName,  ");
                                SqlStringBuilder.Append("             @srcZoneId,@srcZoneName,@destZoneId, @destZoneName,@enabled,@createUserid,@createTime,@guid) ");
                                sqlList.Add(SqlStringBuilder.ToString());

                                parameters = new DynamicParameters();
                                parameters.Add("@transCode", 270);//盘点更新
                                parameters.Add("@cartonNo", sysStocks[j].CartonNo);
                                parameters.Add("@partId", sysStocks[j].PartId);
                                parameters.Add("@partNo", sysStocks[j].PartNo);
                                parameters.Add("@partSpec", sysStocks[j].PartSpec);
                                parameters.Add("@srcLocateId", sysStocks[j].LocateId);//源库位
                                parameters.Add("@srcLocateName", sysStocks[j].LocateName);
                                parameters.Add("@destLocateId", sysStocks[j].LocateId);//目标库位
                                parameters.Add("@destLocateName", sysStocks[j].LocateName);
                                parameters.Add("@oldQty", sysStocks[j].Qty);
                                parameters.Add("@newQty", sysStocks[j].Qty);
                                parameters.Add("@transQty", sysStocks[j].Qty);
                                parameters.Add("@oldStatus", sysStocks[j].Status);
                                parameters.Add("@newStatus", sysStocks[j].Status);
                                parameters.Add("@unit", sysStocks[j].Unit);
                                parameters.Add("@factoryId", sysStocks[j].FactoryId);
                                parameters.Add("@factoryCode", sysStocks[j].FactoryCode);
                                parameters.Add("@srcErpWarehouse", sysStocks[j].ErpWarehouse);
                                parameters.Add("@destErpWarehouse", sysStocks[j].ErpWarehouse);
                                parameters.Add("@srcWarehouseId", sysStocks[j].WarehouseId);
                                parameters.Add("@srcWarehouseName", sysStocks[j].WarehouseName);
                                parameters.Add("@destWarehouseId", sysStocks[j].WarehouseId);
                                parameters.Add("@destWarehouseName", sysStocks[j].WarehouseName);
                                parameters.Add("@srcZoneId", sysStocks[j].ZoneId);
                                parameters.Add("@srcZoneName", sysStocks[j].ZoneName);
                                parameters.Add("@destZoneId", sysStocks[j].ZoneId);
                                parameters.Add("@destZoneName", sysStocks[j].ZoneName);
                                parameters.Add("@enabled", "Y");
                                parameters.Add("@createUserid", 0);
                                parameters.Add("@createTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                                parameters.Add("@guid", Guid.NewGuid().ToString());
                                parametersList.Add(parameters);
                            }
                        }

                        SqlStringBuilder = new StringBuilder(1024);
                        SqlStringBuilder.Append("update SAP_DIFO set SYNFLG='Y',SYNTIM=CONVERT(varchar(50), GETDATE(), 21)  where GUID=@GUID ");//更新同步状态
                        sqlList.Add(SqlStringBuilder.ToString());
                        parameters = new DynamicParameters();
                        parameters.Add("@GUID", sapDifo.Guid);//
                        parametersList.Add(parameters);

                        bool staResult = ExecuteTransaction(sqlList, parametersList);
                        if (staResult == false)
                        {
                            sqlList = new List<string>();
                            parametersList = new List<DynamicParameters>();
                            SqlStringBuilder = new StringBuilder(1024);
                            SqlStringBuilder.Append("update SAP_DIFO set SYNFLG='E',ERRMSG=@ERRMSG,SYNTIM=@SYNTIM  where GUID=@GUID ");//更新同步状态
                            sqlList.Add(SqlStringBuilder.ToString());

                            parameters = new DynamicParameters();
                            parameters.Add("@GUID", sapDifo.Guid);//ID
                            parameters.Add("@ERRMSG", "同步错误，请检查接口数据！");//错误
                            parameters.Add("@SYNTIM", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));//同步时间
                            parametersList.Add(parameters);
                            ExecuteTransaction(sqlList, parametersList);
                            return false;
                        }
                    }
                    else
                    {
                        SqlStringBuilder = new StringBuilder(1024);
                        SqlStringBuilder.Append("update SAP_DIFO set SYNFLG='E',ERRMSG=@ERRMSG,SYNTIM=CONVERT(varchar(50), GETDATE(), 21)  where GUID=@GUID ");//更新同步状态
                        sqlList.Add(SqlStringBuilder.ToString());
                        parameters = new DynamicParameters();
                        parameters.Add("@GUID", sapDifo.Guid);//
                        parameters.Add("@ERRMSG", "同步错误，未查询到对应盘点单信息！");//错误
                        parameters.Add("@SYNTIM", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));//同步时间
                        parametersList.Add(parameters);

                        bool staResult = ExecuteTransaction(sqlList, parametersList);
                    }
                }
                return true;
            }
        }


        #endregion

        #region
        /// <summary>
        /// 获取物流公司信息
        /// </summary>
        /// <returns></returns>
        public List<WmsLogistics> GetLogisticsInfo()
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                StringBuilder sql = new StringBuilder(1024);
                sql.Append("SELECT top 1000 * FROM WMS_LOGISTICS (nolock) ");
                sql.Append("WHERE  SYNFLG = 'N' ");
                sql.Append("ORDER BY RECTIM  ");

                return dbConn.Query<WmsLogistics>(sql.ToString()).ToList();
            }
        }

        /// <summary>
        /// 物流公司信息
        /// </summary>
        /// <param name="wmsLogistics"></param>
        /// <returns></returns>
        public bool InsertLogisticsInfo(List<WmsLogistics> wmsLogistics)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                WmsLogistics logistics = new WmsLogistics();
                StringBuilder SqlStringBuilder;
                List<string> sqlList;
                List<DynamicParameters> parametersList;
                DynamicParameters parameters;
                try
                {
                    StringBuilder factoryStringBuilder = new StringBuilder(1024);
                    factoryStringBuilder.Append("select * from sys_factory (nolock) where enabled='Y'");//工厂代码获取工厂ID
                    List<SysFactory> sysFactory = dbConn.Query<SysFactory>(factoryStringBuilder.ToString()).ToList();
                    for (int k = 0; k < sysFactory.Count; k++)
                    {
                        SqlStringBuilder = new StringBuilder(1024);
                        parameters = new DynamicParameters();

                        for (int i = 0; i < wmsLogistics.Count; i++)
                        {
                            sqlList = new List<string>();
                            parametersList = new List<DynamicParameters>();
                            logistics = wmsLogistics[i];
                            StringBuilder stringBuilder = new StringBuilder();
                            stringBuilder.Append(" SELECT * from wms_logisticsinfo (nolock) WHERE logisticscode='" + logistics.Logisticscode + "' AND factory_code = '" + sysFactory[k].FactoryCode + "' ");
                            List<WmsLogisticsinfo> wmsLogisticsinfos = dbConn.Query<WmsLogisticsinfo>(stringBuilder.ToString()).ToList();
                            if (wmsLogisticsinfos.Count > 0)
                            {
                                SqlStringBuilder = new StringBuilder(1024);
                                SqlStringBuilder.Append("UPDATE dbo.wms_logisticsinfo ");
                                SqlStringBuilder.Append("   SET logisticscode = @logisticscode ,logisticsname = @logisticsname ");
                                SqlStringBuilder.Append("      ,area = @area ,startingprice = @startingprice ");
                                SqlStringBuilder.Append("      ,firstvalue=@firstvalue,pricingrule=@pricingrule");
                                SqlStringBuilder.Append("      ,unit=@unit");
                                SqlStringBuilder.Append("      ,factory_id = @factoryId ,factory_code = @factoryCode ");
                                SqlStringBuilder.Append("      ,enabled = @enabled ,update_userid = @updateUserid ");
                                SqlStringBuilder.Append("      ,update_time = @updateTime ");
                                SqlStringBuilder.Append(" WHERE logisticscode = @logisticscode AND factory_code = @factoryCode ");

                                sqlList.Add(SqlStringBuilder.ToString());

                                parameters = new DynamicParameters();
                                parameters.Add("@logisticscode", logistics.Logisticscode);//物流公司代码
                                parameters.Add("@logisticsname", logistics.Logisticsname);//物流公司名称
                                parameters.Add("@area", logistics.Area);//区域
                                parameters.Add("@startingprice", logistics.Startingprice);//起步价
                                parameters.Add("@firstvalue", logistics.Firstvalue);//首公斤计价
                                parameters.Add("@pricingrule", logistics.Pricingrule);//计价规则
                                parameters.Add("@unit", logistics.Unit);//单位
                                parameters.Add("@factoryId", sysFactory[k].FactoryId);//工厂ID
                                parameters.Add("@factoryCode", sysFactory[k].FactoryCode);//工厂代码

                                parameters.Add("@enabled", logistics.Enabled);//启用
                                parameters.Add("@updateUserid", 0);//更新人
                                parameters.Add("@updateTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));//更新日期

                                parametersList.Add(parameters);
                            }
                            else
                            {
                                SqlStringBuilder = new StringBuilder(1024);
                                SqlStringBuilder.Append("INSERT INTO dbo.wms_logisticsinfo(logisticscode,logisticsname,area,startingprice ");
                                SqlStringBuilder.Append("           ,firstvalue,pricingrule,unit");
                                SqlStringBuilder.Append("           ,factory_id,factory_code,enabled,create_userid,create_time) ");
                                SqlStringBuilder.Append("     VALUES(@logisticscode,@logisticsname,@area,@startingprice ");
                                SqlStringBuilder.Append("           ,@firstvalue,@pricingrule,@unit");
                                SqlStringBuilder.Append("           ,@factoryId,@factoryCode,@enabled,@createUserid,@createTime) ");

                                sqlList.Add(SqlStringBuilder.ToString());

                                parameters = new DynamicParameters();
                                parameters.Add("@logisticscode", logistics.Logisticscode);//物流公司代码
                                parameters.Add("@logisticsname", logistics.Logisticsname);//物流公司名称
                                parameters.Add("@area", logistics.Area);//区域
                                parameters.Add("@startingprice", logistics.Startingprice);//起步价
                                parameters.Add("@firstvalue", logistics.Firstvalue);//首公斤计价
                                parameters.Add("@pricingrule", logistics.Pricingrule);//计价规则
                                parameters.Add("@unit", logistics.Unit);//单位

                                parameters.Add("@factoryId", sysFactory[k].FactoryId);//工厂ID
                                parameters.Add("@factoryCode", sysFactory[k].FactoryCode);//工厂代码

                                parameters.Add("@enabled", logistics.Enabled);//启用
                                parameters.Add("@createUserid", 0);//创建人
                                parameters.Add("@createTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));//创建日期

                                parametersList.Add(parameters);
                            }

                            SqlStringBuilder = new StringBuilder(1024);
                            SqlStringBuilder.Append("update WMS_LOGISTICS set SYNFLG='Y',SYNTIM=@SYNTIM,ERRMSG=''  where LOGISTICSCODE=@LOGISTICSCODE ");//更新同步状态
                            sqlList.Add(SqlStringBuilder.ToString());

                            parameters = new DynamicParameters();
                            parameters.Add("@LOGISTICSCODE", logistics.Logisticscode);//ID
                            parameters.Add("@SYNTIM", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));//同步时间
                            parametersList.Add(parameters);

                            bool staResult = ExecuteTransaction(sqlList, parametersList);
                            if (staResult == false)
                            {
                                sqlList = new List<string>();
                                parametersList = new List<DynamicParameters>();
                                SqlStringBuilder = new StringBuilder(1024);
                                SqlStringBuilder.Append("update WMS_LOGISTICS set SYNFLG='E',ERRMSG=@ERRMSG,SYNTIM=@SYNTIM  where LOGISTICSCODE=@LOGISTICSCODE ");//更新同步状态
                                sqlList.Add(SqlStringBuilder.ToString());

                                parameters = new DynamicParameters();
                                parameters.Add("@LOGISTICSCODE", logistics.Logisticscode);//ID
                                parameters.Add("@ERRMSG", "同步错误，请检查接口数据！");//错误
                                parameters.Add("@SYNTIM", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));//同步时间
                                parametersList.Add(parameters);
                                ExecuteTransaction(sqlList, parametersList);
                                return false;
                            }
                        }
                    }
                    return true;
                }
                catch (Exception ex)
                {
                    sqlList = new List<string>();
                    parametersList = new List<DynamicParameters>();
                    SqlStringBuilder = new StringBuilder(1024);
                    SqlStringBuilder.Append("update WMS_LOGISTICS set SYNFLG='E',ERRMSG=@ERRMSG,SYNTIM=@SYNTIM  where LOGISTICSCODE=@LOGISTICSCODE ");//更新同步状态
                    sqlList.Add(SqlStringBuilder.ToString());

                    parameters = new DynamicParameters();
                    parameters.Add("@LOGISTICSCODE", logistics.Logisticscode);//ID
                    parameters.Add("@ERRMSG",ex.Message);//错误
                    parameters.Add("@SYNTIM", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));//同步时间
                    parametersList.Add(parameters);
                    ExecuteTransaction(sqlList, parametersList);
                    return false;
                }
            }
        }
        #endregion

        public List<WmsWh> GetWareHouse()
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                StringBuilder sql = new StringBuilder(1024);
                sql.Append("SELECT top 1000 * FROM WMS_WH (nolock) ");
                sql.Append("WHERE  SYNFLG = 'N' ");
                sql.Append("ORDER BY RECTIM  ");

                return dbConn.Query<WmsWh>(sql.ToString()).ToList();
            }
        }

        public bool InsertWareHouseInfo(List<WmsWh> wmsWhs)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                WmsWh wareHouse = new WmsWh();
                StringBuilder factoryStringBuilder = new StringBuilder(1024);
                factoryStringBuilder.Append("select * from sys_factory (nolock) where enabled='Y'");//工厂代码获取工厂ID
                List<SysFactory> sysFactory = dbConn.Query<SysFactory>(factoryStringBuilder.ToString()).ToList();
                for (int k = 0; k < sysFactory.Count; k++)
                {
                    StringBuilder SqlStringBuilder = new StringBuilder(1024);
                    DynamicParameters parameters = new DynamicParameters();

                    for (int i = 0; i < wmsWhs.Count; i++)
                    {
                        List<string> sqlList = new List<string>();
                        List<DynamicParameters> parametersList = new List<DynamicParameters>();
                        wareHouse = wmsWhs[i];
                        StringBuilder stringBuilder = new StringBuilder();
                        stringBuilder.Append(" SELECT * from sys_warehouse (nolock) WHERE warehouse_name='" + wareHouse.Whcode + "' AND factory_code = '" + sysFactory[k].FactoryCode + "' ");
                        List<SysWarehouse> sysVendors = dbConn.Query<SysWarehouse>(stringBuilder.ToString()).ToList();
                        if (sysVendors.Count > 0)
                        {
                            SqlStringBuilder = new StringBuilder(1024);
                            SqlStringBuilder.Append(" UPDATE dbo.sys_warehouse ");
                            SqlStringBuilder.Append("   SET warehouse_name = @warehouseCode ,warehouse_desc = @wareHouseDesc ,factory_id = @factoryId ");
                            SqlStringBuilder.Append("      ,factory_code = @factoryCode ,enabled = @enabled ,update_userid = @updateUserid ");
                            SqlStringBuilder.Append("      ,update_time = @updateTime ");
                            SqlStringBuilder.Append(" WHERE warehouse_name = @warehouseCode AND factory_code = @factoryCode ");

                            sqlList.Add(SqlStringBuilder.ToString());

                            parameters = new DynamicParameters();
                            parameters.Add("@warehouseCode", wareHouse.Whcode);//物料编码
                            parameters.Add("@wareHouseDesc", wareHouse.Whname);//物料描述

                            parameters.Add("@factoryId", sysFactory[k].FactoryId);//工厂ID
                            parameters.Add("@factoryCode", sysFactory[k].FactoryCode);//工厂代码

                            parameters.Add("@enabled", wareHouse.Enabled);//是否启用
                            parameters.Add("@updateUserid", 0);//更新人
                            parameters.Add("@updateTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));//更新日期

                            parametersList.Add(parameters);
                        }
                        else
                        {
                            SqlStringBuilder = new StringBuilder(1024);
                            SqlStringBuilder.Append("INSERT INTO dbo.sys_warehouse(warehouse_name,warehouse_desc ");
                            SqlStringBuilder.Append("           ,factory_id,factory_code,enabled,create_userid,create_time) ");
                            SqlStringBuilder.Append("     VALUES(@warehouse_name,@warehouse_desc ");
                            SqlStringBuilder.Append("           ,@factoryId,@factoryCode,@enabled,@createUserid,@createTime) ");

                            sqlList.Add(SqlStringBuilder.ToString());

                            parameters = new DynamicParameters();
                            parameters.Add("@warehouse_name", wareHouse.Whcode);//仓库编码
                            parameters.Add("@warehouse_desc", wareHouse.Whname);//仓库描述

                            parameters.Add("@factoryId", sysFactory[k].FactoryId);//工厂ID
                            parameters.Add("@factoryCode", sysFactory[k].FactoryCode);//工厂代码

                            parameters.Add("@enabled", wareHouse.Enabled);//启用
                            parameters.Add("@createUserid", 0);//创建人
                            parameters.Add("@createTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));//创建日期

                            parametersList.Add(parameters);

                        }

                        SqlStringBuilder = new StringBuilder(1024);
                        SqlStringBuilder.Append("update WMS_WH set SYNFLG='Y',SYNTIM=@SYNTIM where WHCODE=@WHCODE ");//更新同步状态
                        sqlList.Add(SqlStringBuilder.ToString());

                        parameters = new DynamicParameters();
                        parameters.Add("@WHCODE", wareHouse.Whcode);//code
                        parameters.Add("@SYNTIM", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));//同步时间
                        parametersList.Add(parameters);

                        bool staResult = ExecuteTransaction(sqlList, parametersList);
                        if (staResult == false)
                        {
                            sqlList = new List<string>();
                            parametersList = new List<DynamicParameters>();
                            SqlStringBuilder = new StringBuilder(1024);
                            SqlStringBuilder.Append("update WMS_WH set SYNFLG='E',ERRMSG=@ERRMSG,SYNTIM=@SYNTIM  where WHCODE=@WHCODE ");//更新同步状态
                            sqlList.Add(SqlStringBuilder.ToString());

                            parameters = new DynamicParameters();
                            parameters.Add("@WHCODE", wareHouse.Whcode);//ID
                            parameters.Add("@ERRMSG", "同步错误，请检查接口数据！");//错误
                            parameters.Add("@SYNTIM", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));//同步时间
                            parametersList.Add(parameters);
                            ExecuteTransaction(sqlList, parametersList);
                            return false;
                        }
                    }
                }
                return true;
            }
        }

        public List<WmsZone> GetZone()
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                StringBuilder sql = new StringBuilder(1024);
                sql.Append("SELECT top 1000 * FROM WMS_ZONE (nolock) ");
                sql.Append("WHERE  SYNFLG = 'N' ");
                sql.Append("ORDER BY RECTIM  ");

                return dbConn.Query<WmsZone>(sql.ToString()).ToList();
            }
        }

        public bool InsertZoneInfo(List<WmsZone> wmsZones)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                WmsZone zone = new WmsZone();
                StringBuilder factoryStringBuilder = new StringBuilder(1024);
                factoryStringBuilder.Append("select * from sys_factory (nolock) where enabled='Y'");//工厂代码获取工厂ID
                List<SysFactory> sysFactory = dbConn.Query<SysFactory>(factoryStringBuilder.ToString()).ToList();
                for (int k = 0; k < sysFactory.Count; k++)
                {
                    StringBuilder SqlStringBuilder = new StringBuilder(1024);
                    DynamicParameters parameters = new DynamicParameters();

                    for (int i = 0; i < wmsZones.Count; i++)
                    {
                        List<string> sqlList = new List<string>();
                        List<DynamicParameters> parametersList = new List<DynamicParameters>();
                        zone = wmsZones[i];
                        StringBuilder warehouse = new StringBuilder();
                        warehouse.Append("SELECT * FROM sys_warehouse (nolock) WHERE warehouse_name='" + zone.Warehousename + "'");
                        List<SysWarehouse> sysWarehouses = dbConn.Query<SysWarehouse>(warehouse.ToString()).ToList();
                        if (sysWarehouses.Count == 0)
                        {
                            sqlList = new List<string>();
                            parametersList = new List<DynamicParameters>();
                            SqlStringBuilder = new StringBuilder(1024);
                            SqlStringBuilder.Append("update WMS_ZONE set SYNFLG='E',ERRMSG=@ERRMSG,SYNTIM=@SYNTIM  where ZONENAME=@ZONENAME ");//更新同步状态
                            sqlList.Add(SqlStringBuilder.ToString());

                            parameters = new DynamicParameters();
                            parameters.Add("@ZONENAME", zone.Zonename);//name
                            parameters.Add("@ERRMSG", $"请检查仓库{zone.Warehousename},是否存在!");//错误
                            parameters.Add("@SYNTIM", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));//同步时间
                            parametersList.Add(parameters);
                            ExecuteTransaction(sqlList, parametersList);
                            throw new Exception($"请检查仓库{zone.Warehousename},是否存在!");
                        }
                        StringBuilder stringBuilder = new StringBuilder();
                        stringBuilder.Append(" SELECT * from sys_zone (nolock) WHERE zone_name='" + zone.Zonename + "' AND factory_code = '" + sysFactory[k].FactoryCode + "' ");
                        List<SysZone> sysVendors = dbConn.Query<SysZone>(stringBuilder.ToString()).ToList();
                        if (sysVendors.Count > 0)
                        {
                            SqlStringBuilder = new StringBuilder(1024);
                            SqlStringBuilder.Append(" UPDATE dbo.sys_zone ");
                            SqlStringBuilder.Append("   SET zone_name = @zoneName ,zone_desc = @zoneDesc ,factory_id = @factoryId ");
                            SqlStringBuilder.Append("      ,warehouse_id=@warehouseId,erp_warehouse=@erpWarehouse");
                            SqlStringBuilder.Append("      ,factory_code = @factoryCode ,enabled = @enabled ,update_userid = @updateUserid ");
                            SqlStringBuilder.Append("      ,update_time = @updateTime,warehouse_name=@warehouseName ");
                            SqlStringBuilder.Append(" WHERE locate_name = @locateName AND factory_code = @factoryCode ");

                            sqlList.Add(SqlStringBuilder.ToString());

                            parameters = new DynamicParameters();
                            parameters.Add("@zoneName", zone.Zonename);//仓位名称
                            parameters.Add("@zoneDesc", zone.Zonedesc);//仓位描述
                            parameters.Add("@erpWarehouse", zone.Erpwarehouse);//ERP仓库
                            parameters.Add("@warehouseName", zone.Warehousename);//仓库名称
                            parameters.Add("@warehouseId", sysWarehouses.FirstOrDefault().WarehouseId);
                            parameters.Add("@factoryId", sysFactory[k].FactoryId);//工厂ID
                            parameters.Add("@factoryCode", sysFactory[k].FactoryCode);//工厂代码

                            parameters.Add("@enabled", zone.Enabled);//是否启用
                            parameters.Add("@updateUserid", 0);//更新人
                            parameters.Add("@updateTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));//更新日期

                            parametersList.Add(parameters);
                        }
                        else
                        {
                            SqlStringBuilder = new StringBuilder(1024);
                            SqlStringBuilder.Append("INSERT INTO dbo.sys_zone(zone_name,zone_desc ");
                            SqlStringBuilder.Append("           ,warehouse_name,warehouse_id,erp_warehouse");
                            SqlStringBuilder.Append("           ,factory_id,factory_code,enabled,create_userid,create_time) ");
                            SqlStringBuilder.Append("     VALUES(@zoneName,@zoneDesc ");
                            SqlStringBuilder.Append("           ,@warehouseName,@warehouseId,@erpWarehouse");
                            SqlStringBuilder.Append("           ,@factoryId,@factoryCode,@enabled,@createUserid,@createTime) ");

                            sqlList.Add(SqlStringBuilder.ToString());

                            parameters = new DynamicParameters();
                            parameters.Add("@zoneName", zone.Zonename);//仓位名称
                            parameters.Add("@zoneDesc", zone.Zonedesc);//仓位描述
                            parameters.Add("@erpWarehouse", zone.Erpwarehouse);//ERP仓库
                            parameters.Add("@warehouseId", sysWarehouses.FirstOrDefault().WarehouseId);//仓库ID
                            parameters.Add("@warehouseName", zone.Warehousename);//仓库名称

                            parameters.Add("@factoryId", sysFactory[k].FactoryId);//工厂ID
                            parameters.Add("@factoryCode", sysFactory[k].FactoryCode);//工厂代码

                            parameters.Add("@enabled", zone.Enabled);//启用
                            parameters.Add("@createUserid", 0);//创建人
                            parameters.Add("@createTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));//创建日期

                            parametersList.Add(parameters);

                        }

                        SqlStringBuilder = new StringBuilder(1024);
                        SqlStringBuilder.Append("update WMS_ZONE set SYNFLG='Y',SYNTIM=@SYNTIM where ZONENAME=@ZONENAME ");//更新同步状态
                        sqlList.Add(SqlStringBuilder.ToString());

                        parameters = new DynamicParameters();
                        parameters.Add("@ZONENAME", zone.Zonename);//name
                        parameters.Add("@SYNTIM", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));//同步时间
                        parametersList.Add(parameters);

                        bool staResult = ExecuteTransaction(sqlList, parametersList);
                        if (staResult == false)
                        {
                            sqlList = new List<string>();
                            parametersList = new List<DynamicParameters>();
                            SqlStringBuilder = new StringBuilder(1024);
                            SqlStringBuilder.Append("update WMS_ZONE set SYNFLG='E',ERRMSG=@ERRMSG,SYNTIM=@SYNTIM  where ZONENAME=@ZONENAME ");//更新同步状态
                            sqlList.Add(SqlStringBuilder.ToString());

                            parameters = new DynamicParameters();
                            parameters.Add("@ZONENAME", zone.Zonename);//name
                            parameters.Add("@ERRMSG", "同步错误，请检查接口数据！");//错误
                            parameters.Add("@SYNTIM", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));//同步时间
                            parametersList.Add(parameters);
                            ExecuteTransaction(sqlList, parametersList);
                            return false;
                        }
                    }
                }
                return true;
            }
        }

        public List<WmsToqce> GetWmsToqcs()
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                StringBuilder sql = new StringBuilder(1024);
                sql.Append("SELECT top 1000 * FROM WMS_TOQCE (nolock) ");
                sql.Append("WHERE  SYNFLG = 'N' ");
                sql.Append("ORDER BY RECTIM  ");

                return dbConn.Query<WmsToqce>(sql.ToString()).ToList();
            }
        }

        /// <summary>
        /// 添加质检结果
        /// </summary>
        /// <param name="wmsToqcs"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public bool InsertQCInfo(List<WmsToqce> wmsToqcs)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                WmsToqce toqc = new WmsToqce();
                StringBuilder factoryStringBuilder = new StringBuilder(1024);
                factoryStringBuilder.Append("select * from sys_factory (nolock) where enabled='Y'");//工厂代码获取工厂ID
                List<SysFactory> sysFactory = dbConn.Query<SysFactory>(factoryStringBuilder.ToString()).ToList();
                for (int k = 0; k < sysFactory.Count; k++)
                {
                    StringBuilder SqlStringBuilder = new StringBuilder(1024);
                    DynamicParameters parameters = new DynamicParameters();

                    for (int i = 0; i < wmsToqcs.Count; i++)
                    {
                        List<string> sqlList = new List<string>();
                        List<DynamicParameters> parametersList = new List<DynamicParameters>();
                        toqc = wmsToqcs[i];
                        StringBuilder parts = new StringBuilder();
                        parts.Append("SELECT * FROM sys_part (nolock) WHERE  part_no='"+toqc.PartNo+"'");
                        List<SysPart> sysParts = dbConn.Query<SysPart>(parts.ToString()).ToList();
                        if (sysParts.Count == 0)
                        {
                            sqlList = new List<string>();
                            parametersList = new List<DynamicParameters>();
                            SqlStringBuilder = new StringBuilder(1024);
                            SqlStringBuilder.Append("update WMS_TOQCE set SYNFLG='E',ERRMSG=@ERRMSG,SYNTIM=@SYNTIM  where ETENR=@ETENR");//更新同步状态
                            sqlList.Add(SqlStringBuilder.ToString());

                            parameters = new DynamicParameters();
                            parameters.Add("@ETENR", toqc.Etenr);
                            parameters.Add("@ERRMSG", "同步错误，请检查接口数据！");//错误
                            parameters.Add("@SYNTIM", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));//同步时间
                            parametersList.Add(parameters);
                            ExecuteTransaction(sqlList, parametersList);
                            throw new Exception($"请检查物料{toqc.PartNo},是否存在!");
                        }
                        StringBuilder stringBuilder = new StringBuilder();
                        stringBuilder.Append(" SELECT * FROM wms_qc_result (nolock) WHERE order_no='" + toqc.Etenr + "' and part_no='" + toqc.PartNo + "' AND factory_code = '" + sysFactory[k].FactoryCode + "' ");
                        List<WmsQcResult> wmsQcResults = dbConn.Query<WmsQcResult>(stringBuilder.ToString()).ToList();
                        if (wmsQcResults.Count > 0)
                        {
                            SqlStringBuilder = new StringBuilder(1024);
                            SqlStringBuilder.Append(" UPDATE dbo.wms_qc_result ");
                            SqlStringBuilder.Append("   SET qty = @Qty ,ok_qty = @okQty ,factory_id = @factoryId ");
                            SqlStringBuilder.Append("      ,nc_qty=@ncQty,surplusQty=@surplusQty");
                            SqlStringBuilder.Append("      ,factory_code = @factoryCode ,enabled = @enabled ,update_userid = @updateUserid ");
                            SqlStringBuilder.Append("      ,update_time = @updateTime ");
                            SqlStringBuilder.Append(" WHERE order_no = @orderNo and part_no=@partNo AND factory_code = @factoryCode ");

                            sqlList.Add(SqlStringBuilder.ToString());

                            parameters = new DynamicParameters();
                            parameters.Add("@orderNo", toqc.Etenr);
                            parameters.Add("@partNo", toqc.PartNo);
                            parameters.Add("@Qty", toqc.PartNoNum);//检验数量
                            parameters.Add("@okQty", toqc.Zdev);//合格数量
                            parameters.Add("@ncQty", toqc.NZdev);//不合格数量
                            parameters.Add("@surplusQty",Convert.ToInt32( toqc.NZdev)+wmsQcResults.FirstOrDefault().surplusQty);//不合格累加
                            
                            parameters.Add("@factoryId", sysFactory[k].FactoryId);//工厂ID
                            parameters.Add("@factoryCode", sysFactory[k].FactoryCode);//工厂代码

                            parameters.Add("@enabled", 'Y');//是否启用
                            parameters.Add("@updateUserid", 0);//更新人
                            parameters.Add("@updateTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));//更新日期

                            parametersList.Add(parameters);
                        }
                        else
                        {
                            SqlStringBuilder = new StringBuilder(1024);
                            SqlStringBuilder.Append("INSERT INTO dbo.wms_qc_result(order_no,part_id ");
                            SqlStringBuilder.Append("           ,part_no,part_spec,lot_no");
                            SqlStringBuilder.Append("           ,qty,ok_qty,nc_qty,surplusQty,item_status");
                            SqlStringBuilder.Append("           ,factory_id,factory_code,enabled,create_userid,create_time) ");
                            SqlStringBuilder.Append("     VALUES(@orderNo,@partId ");
                            SqlStringBuilder.Append("           ,@partNo,@partSpec,@lotNo");
                            SqlStringBuilder.Append("           ,@Qty,@okQty,@ncQty,@surplusQty,@itemStatus");
                            SqlStringBuilder.Append("           ,@factoryId,@factoryCode,@enabled,@createUserid,@createTime) ");

                            sqlList.Add(SqlStringBuilder.ToString());

                            StringBuilder stringBuilder1 = new StringBuilder();
                            stringBuilder1.Append(" SELECT * FROM wms_qc_detail (nolock) WHERE order_no='" + toqc.Etenr + "' and part_no='" + toqc.PartNo + "' AND factory_code = '" + sysFactory[k].FactoryCode + "' ");
                            List<WmsQcDetail> qcDetails = dbConn.Query<WmsQcDetail>(stringBuilder1.ToString()).ToList();


                            parameters = new DynamicParameters();
                            parameters.Add("@orderNo", toqc.Etenr);//质检单号
                            parameters.Add("@partId", sysParts.FirstOrDefault().PartId);//零件ID
                            parameters.Add("@partNo", toqc.PartNo);//零件
                            parameters.Add("@partSpec", sysParts.FirstOrDefault().PartSpec);//零件描述
                            parameters.Add("@lotNo", qcDetails.Count==0?null:qcDetails.FirstOrDefault().LotNo);//批次
                            parameters.Add("@Qty", toqc.PartNoNum);
                            parameters.Add("@okQty", toqc.Zdev);
                            parameters.Add("@ncQty", toqc.NZdev);
                            parameters.Add("@surplusQty", toqc.NZdev);
                            parameters.Add("@itemStatus", 10);
                            parameters.Add("@factoryId", sysFactory[k].FactoryId);//工厂ID
                            parameters.Add("@factoryCode", sysFactory[k].FactoryCode);//工厂代码

                            parameters.Add("@enabled", 'Y');//启用
                            parameters.Add("@createUserid", 0);//创建人
                            parameters.Add("@createTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));//创建日期

                            parametersList.Add(parameters);

                        }

                        SqlStringBuilder = new StringBuilder(1024);
                        SqlStringBuilder.Append("update WMS_TOQCE set SYNFLG='Y',SYNTIM=@SYNTIM where ETENR=@ETENR AND PARTNO=@PARTNO ");//更新同步状态
                        sqlList.Add(SqlStringBuilder.ToString());

                        parameters = new DynamicParameters();
                        parameters.Add("@ETENR", toqc.Etenr);
                        parameters.Add("@PARTNO", toqc.PartNo);
                        parameters.Add("@SYNTIM", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));//同步时间
                        parametersList.Add(parameters);

                        bool staResult = ExecuteTransaction(sqlList, parametersList);
                        if (staResult == false)
                        {
                            sqlList = new List<string>();
                            parametersList = new List<DynamicParameters>();
                            SqlStringBuilder = new StringBuilder(1024);
                            SqlStringBuilder.Append("update WMS_TOQCE set SYNFLG='E',ERRMSG=@ERRMSG,SYNTIM=@SYNTIM  where ETENR=@ETENR AND PARTNO=@PARTNO ");//更新同步状态
                            sqlList.Add(SqlStringBuilder.ToString());

                            parameters = new DynamicParameters();
                            parameters.Add("@ETENR", toqc.Etenr);
                            parameters.Add("@PARTNO", toqc.PartNo);
                            parameters.Add("@ERRMSG", "同步错误，请检查接口数据！");//错误
                            parameters.Add("@SYNTIM", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));//同步时间
                            parametersList.Add(parameters);
                            ExecuteTransaction(sqlList, parametersList);
                            return false;
                        }
                    }
                }
                return true;
            }
        }

    }
}
